2016-01-26 114 views
4

我试图做这样的事情不必手动编写了一系列test块内部ExUnit.test声明:是否有可能有一个Enum.each

test_cases = %{ 
    "foo" => 1, 
    "bar" => 2, 
    "baz" => 3, 
} 

Enum.each(test_cases, fn({input, expected_output}) -> 
    test "for #{input}" do 
    assert(Mymodule.myfunction input) == expected_output 
    end 
end) 

但是这段代码运行时我得到了线路assert(Mymodule.myfunction input) == expected_output上的错误undefined function input/0

有没有办法实现我想要的?

回答

6

是的,它是可能的,你只需要unquoteinputexpected_output你传递给test/2do块内。

test_cases = %{ 
    "foo" => 1, 
    "bar" => 2, 
    "baz" => 3, 
} 

Enum.each test_cases, fn({input, expected_output}) -> 
    test "for #{input}" do 
    assert Mymodule.myfunction(unquote(input)) == unquote(expected_output) 
    end 
end 

顺便说一句,你,你用刚Mymodule.myfunction input作为参数调用assert/1,而不是Mymodule.myfunction(input) == expected_output(这是你试图断言的表达式)曾在assert线括号错误。

相关问题