gpt4 book ai didi

unit-testing - 如何在没有模拟的情况下记录/验证单元测试中的方法调用?

转载 作者:行者123 更新时间:2023-12-04 17:52:50 26 4
gpt4 key购买 nike

如何在单元测试中编写期望?

这是一个例子:

defmodule MyAPIModule do
@url "http://example.com/path"

def get_something(http_module \\ HTTPoison) do
http_module.get!(@url, [], [])
end
end

这是我的测试:
defmodule MyAPIModuleTest do
use ExUnit.Case

test "Runs the get! method with no headers and no params" do
MyAPIModule.get_something(HttpSpy)
# 1) assert that get! was called
# 2) assert [] == headers
# 3) assert [] == params
# 4) assert "http://example.com/path" == url
end
end

defmodule HttpSpy do
def get!(url, headers, params) do
#
end
end

我的问题是不变性。我不能简单地在 HttpSpy 模块中创建一个列表并将方法调用及其参数记录到该列表中。

所以我尝试以这种方式更改 HttpSpy:
defmodule HttpSpy do
def start(listener) do
spawn_link(__MODULE__, loop, [listener])
end

def loop(listener) do
receive do

end
end

def get!(url, headers, params) do

end
end

我将测试更改为:
test "Runs the get! method with no headers and no params"
spy = HttpSpy.start(self)
MyAPIModule.get_something(HttpSpy)
receive do
{^spy, method_call} -> flunk("wrong method call")
after 1000 -> flunk("timeout")
end
end

但我被困住了。 HttpSpy.get!不知道测试产生的 HttpSpy 进程的 PID。
因此HttpSpy.get!无法向在循环方法中等待的进程发送消息。
因此,循环方法永远不会将调用的函数及其参数发送给测试(我称之为监听器)。

我意识到我想要的基本上是模拟和期望,但我想找到惯用的方式(= 没有模拟)来做到这一点。

最佳答案

帕特里克给出了一个很好的答案,这将是我的第一个方法。但是,如果您无法直接访问 spy 返回的结果,您可以向自己发送一条消息:

# In the spy
send self(), :get_was_called

# In the test
assert_received :get_was_called

关于unit-testing - 如何在没有模拟的情况下记录/验证单元测试中的方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32724586/

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