gpt4 book ai didi

erlang - 如何使用 Meck 在 Erlang 中模拟对象?

转载 作者:行者123 更新时间:2023-12-04 13:19:46 25 4
gpt4 key购买 nike

好的,我正在使用 Meck,但我迷路了。我的第一语言(我已经写了大约 7 个月了)是 Ruby,所以我似乎还无法将我的大脑包裹在 Meck mocking 上。我确实得到了 Ruby 的 mock 。希望有人可以帮助我。另外,我只写了一周的 Erlang。

更新了代码(但模拟仍然不起作用)...

我有一个 Erlang console_io 提示器模块,如下所示:

    -module(prompter).
-export([prompt/1, guess/0]).

prompt(Message) ->
console_io:gets(Message).

gets() ->
{_, [Input]} = io:fread("Enter: ", "~s"),
Input.

guess() ->
Guess_Input = gets(),
Guess_List = convert_guess_to_list(Guess_Input).

convert_guess_to_list(Guess_Input) ->
re:split(Guess_Input, "", [{return, list}, trim]).

我的测试现在看起来像这样:
    -module(prompter_test).
-include_lib("eunit/include/eunit.hrl").

guess_1_test() ->
meck:new(prompter),
meck:expect(prompter, gets, fun() -> "aaaa" end),
?assertEqual(prompter:guess(), ["a","a","a","a"]),
?assert(meck:validate(prompter)),
meck:unload(prompter).

我得到的错误是:
    Eshell V5.9.3.1  (abort with ^G)
1> prompter_test: guess_1_test (module 'prompter_test')...*failed*
in function prompter:guess/0
called as guess()
in call from prompter_test:guess_1_test/0 (test/prompter_test.erl, line 10)
in call from prompter_test:guess_1_test/0
**error:undef

我想在我的测试中模拟( stub ?)gets函数,这样gets将返回“aaaa”,然后当我在get_guess()上断言时它应该等于[“a”,“a”,“a”,“a” ]。

我该怎么做呢?

最佳答案

有两个问题:

  • prompter模块有两个导出函数,但你只能用 gets 模拟其中一个(meck:expect) .默认情况下,Meck 创建一个仅包含您明确模拟的函数的新模块。您可以使用 passthrough 来更改它。选项:
    meck:new(prompter, [passthrough]),
  • 当你模拟 gets函数,所有以模块为前缀的调用(即 prompter:gets() )都被拦截,但 Meck 没有办法(还没有?)拦截内部调用(例如 gets() 函数中的 guess 调用),所以你仍然会得到函数的非模拟版本。没有完全令人满意的方法可以避免这种情况。您可以更改 guess 中的调用至prompter:gets() , 或者你可以移动 gets进入一个单独的模块并模拟它。
  • 关于erlang - 如何使用 Meck 在 Erlang 中模拟对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16510189/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com