Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Elixir 如何通过命名的设置函数传递上下文以测试描述块中的宏_Elixir_Elixir Mix_Ex Unit - Fatal编程技术网

Elixir 如何通过命名的设置函数传递上下文以测试描述块中的宏

Elixir 如何通过命名的设置函数传递上下文以测试描述块中的宏,elixir,elixir-mix,ex-unit,Elixir,Elixir Mix,Ex Unit,查看ExUnit文档,您可以使用以下模式将属性添加到上下文结构中: defmodule KVTest do use ExUnit.Case setup do {:ok, pid} = KV.start_link {:ok, pid: pid} # "[pid: pid]" also appears to work... end test "stores key-value pairs", context do assert KV.put(con

查看ExUnit文档,您可以使用以下模式将属性添加到
上下文
结构中:

defmodule KVTest do
  use ExUnit.Case

  setup do
    {:ok, pid} = KV.start_link
    {:ok, pid: pid}
    # "[pid: pid]" also appears to work...
  end

  test "stores key-value pairs", context do
    assert KV.put(context[:pid], :hello, :world) == :ok
    assert KV.get(context[:pid], :hello) == :world

    # "context.pid" also appears to work...
  end
end
但是当使用
description
宏块时,建议您使用以下表格为测试提供设置功能:

defmodule UserManagementTest do
  use ExUnit.Case, async: true

  describe "when user is logged in and is an admin" do
    setup [:log_user_in, :set_type_to_admin]

    test ...
  end

  describe "when user is logged in and is a manager" do
    setup [:log_user_in, :set_type_to_manager]

    test ...
  end

  defp log_user_in(context) do
    # ...
  end
end
这很好,但是在使用
descripe
宏和命名设置时,没有提到如何向上下文结构添加新属性以用于测试

到目前为止,我已经尝试过(快速总结):


以这种方式为描述块创建设置函数时,是否确实可以操纵测试套件上下文?

您正确地完成了设置部分。命名的设置函数将上下文作为参数,其返回值将自动合并到上下文中。因此,实际上您已经有了测试可用的
:test

您只需要在测试中获取上下文作为第二个参数,如下所示:

描述“当用户登录并且是管理员时”是否
设置[:测试]
测试“做正确的事情”,上下文做
IO.inspect(上下文)#不会显示为零
结束
结束
但是,更有趣的是,您可以使用模式匹配从上下文中获取所需的确切关键点:

描述“当用户登录并且是管理员时”是否
设置[:测试]
测试“做正确的事”,%{test:test}do
IO.检查(测试)#“你好”
结束
结束

那么仅仅从
log\u user\u中返回地图或关键字列表对您不起作用?您的尝试也有语法错误。错误<代码>设置[:测试]
你是说?很可能还有其他人。。。但是是的,到目前为止,我已经尝试了
{test:“HALLO”}
[test:“HALLO”]
%{test:“HALLO”}
。使用常规的
设置
宏是可以的。Tbh Dogbert,在我提供的示例中找出语法错误,引导我返回实际代码,并找出我的错误。将接受下面的答案,尽管这是事实,因为它是正确的。这是正确的,但它非常令人困惑,因为这个问题对私有函数和上下文键使用了相同的名称。
  ...
  describe "when user is logged in and is a manager" do
    setup [:test]

    test(context) do
       IO.puts("#{ inspect context }") # Comes up as 'nil'
    end
  end

  defp test(context) do
    [test: "HALLO"]
  end
  ...