2017-05-27 41 views
2

我正在使用Erlang的EUnit来测试应用程序的单元。EUnit的assertMatch中有多个子句?

我想断言一定的测试值是2和3之间There's no built-in support for this,所以我试图用一对后卫的,是这样的:

myTestCase -> 
    ?assertMatch({ok, V} when V>2, V<3, 
       unitUnderTest() % expected to return 2.54232... 
). 

这种尝试使用guard syntaxandalso

但是,这不起作用,大概是因为Erlang的解析器无法区分assertMatch的多个参数和多个参数之间的区别。我尝试用圆括号包装各种东西,但没有找到任何有效的东西。另一方面,当我将表达式简化为一个子句时,它就成功了。

有没有办法在这里表达多个子句?

回答

1

不能在语法使用逗号,只是因为那时assertMatch被解释为一个宏用3 - 或更多 - 的参数,而没有定义是什么?。但是它的语法和其他功能也适用。你为什么不使用:

fok() -> {ok,2.7}. 

fko() -> {ok,3.7}. 

myTestCase(F) -> 
    F1 = fun() -> apply(?MODULE,F,[]) end, 
    ?assertMatch({ok, V} when V>2 andalso V<3, F1()). 

测试:

1> c(test). 
{ok,test} 
2> test:myTestCase(fok). 
ok 
3> test:myTestCase(fko). 
** exception error: {assertMatch, 
         [{module,test}, 
         {line,30}, 
         {expression,"F1 ()"}, 
         {pattern,"{ ok , V } when V > 2 andalso V < 3"}, 
         {value,{ok,3.7}}]} 
    in function test:'-myTestCase/1-fun-1-'/1 (test.erl, line 30) 
4> 
1

然而,这是不行的,大概是因为Erlang的解析器不能 告诉多重防护装置和多个参数之间的差异 assertMatch

eunit docs明确地警告说:

assertMatch(GuardedPattern, Expr)

GuardedPattern可以是任何东西您可以在案例子句中的 - >符号的左侧 上书写,但不能包含以逗号分隔的 警卫测试。

如何:

-module(my). 
-compile(export_all). 
-include_lib("eunit/include/eunit.hrl"). 

f() -> 
    {ok, 3}. 


f_test() -> 
    ?LET({ok, X}, f(), ?assertMatch(true, X>2 andalso X<4)). 
+0

你可以只用''替换assertMatch(真的,EXP)'断言(EXP)'有?。 –