0

我正在使用 meck 测试我的 gen_server mymodule。特别是我使用 meck按照此处httpc提供的说明进行模拟。

这是我从测试中提取的一些代码:

do_some_tests_() ->
  {foreach,
   fun start/0,
   fun stop/1,
   [fun do_some_stuff/1,
    fun do_some_other_stuff/1
   ]}.

start() ->
  {ok, _} = mymodule:start_link(),
  meck:new(httpc),
  _Pid = self().

stop(_) ->
  meck:unload(httpc), 
  mymodule:stop().

do_some_stuff(Pid) ->
  %% here i use meck
  meck:expect(httpc, request, 
    fun(post, {_URL, _Header, ContentType, Body}, [], []) ->
        Reply = "Data to send back"
        Pid ! {ok, {{"", 200, ""}, [], Reply}}
    end),
  %% here i do the post request
  mymodule:myfunction(Body),
  receive 
    Any -> 
      [
       ?_assertMatch({ok, {{_, 200, _}, [], _}}, Any), 
       ?_assert(meck:validate(httpc))
      ]
  end.

使用此代码,我可以运行测试,但仍有两件事我无法理解:

1)在结果中我得到类似的东西:

mymodule_test:43: do_some_stuff...ok
mymodule_test:43: do_some_stuff...ok
mymodule_test:53: do_some_other_stuff...ok
mymodule_test:53: do_some_other_stuff...ok

是否有可能每次测试只得到一条而不是两条?

2) 如何为每个测试添加口语描述?

4

1 回答 1

3

该函数do_some_stuff(Pid)生成两个测试,因此检查和显示都非常正常。

但是,您可以为每个生成器和测试添加名称/描述:

do_some_tests_() -> 
  {foreach,
  fun start/0,
  fun stop/1,
  [{"Doing some stuff" , fun do_some_stuff/1},
   {"Doing some other stuff" , fun do_some_other_stuff/1}
  ]}.




do_some_stuff(Pid) ->
  %% [code]
  [
   {"Check 200" , ?_assertMatch({ok, {{_, 200, _}, [], _}}, Any)}, 
   {"Check httpc" , ?_assert(meck:validate(httpc))}
  ]
  end.

这应该显示以下内容:

module 'MyModule'
  Doing Some Stuff
    module:57: do_some_stuff (Check 200)...ok
    module:58: do_some_stuff (Check httpc)...ok

在 EUnit 中,这些被称为“ titles ”:

标题

任何测试或测试集 T 都可以用标题进行注释,方法是将其包装在一对 {Title, T} 中,其中 Title 是一个字符串。为方便起见,通常使用元组表示的任何测试都可以简单地给定一个标题字符串作为第一个元素,即编写 {"The Title", ...} 而不是像 {"The Title ",{...}}。

http://www.erlang.org/doc/apps/eunit/chapter.html#id61107

于 2013-08-12T08:16:37.820 回答