【问题标题】:Correct way to use meck with foreach将 meck 与 foreach 一起使用的正确方法
【发布时间】:2013-08-10 17:01:13
【问题描述】:

我正在使用 meck 测试我的 gen_server mymodule。特别是,我按照here 提供的说明使用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) 如何为每个测试添加口语描述?

【问题讨论】:

    标签: erlang eunit meck


    【解决方案1】:

    函数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

    【讨论】:

    • 你好。我可以获得单个描述(例如,检查 200),但如果我尝试放置主要描述(例如,做一些事情),我会得到:未定义 *** 错误的测试描述符 ***
    猜你喜欢
    • 2014-08-30
    • 2011-10-05
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    相关资源
    最近更新 更多