我如何模拟类似于 python requests-mock 工作方式的特定 api 调用:
with requests_mock.mock() as m:
m.get('http://test.com', text='data')
requests.get('http://test.com').text
在这个例子中,在 with 语句中对 http://test.com
的每次调用都将被模拟
所以在 Elixir 中,例如,我有这个:
defmodule API do
# makes a call to an external API I dont want to test
def make_call do
...
end
end
defmodule Item do
alias API
# function I actually want to test
def build_request do
API.make_call
# stuff I want to test
end
end
假设我想测试 build_request
模拟 make_call
我试过这个包 https://github.com/jjh42/mock但是这个包所做的是用例如 make_call
方法的模拟覆盖整个 API 模块,但是你也失去了 API 模块的所有其他功能,我不希望这样。
我如何模拟该调用?
在另一个例子中,我看到了 https://hashrocket.com/blog/posts/mocking-api-s-with-elixir
# mocking a github api call directly
@github_api.make_request(:get, "/users/#{username}")
但这是同一个问题,它在测试中直接模拟请求,我的问题是模拟需要在 inner 函数中完成而不是立即。
最佳答案
Dependency injection是你的 friend :
def build_request(caller \\ API) do
caller.make_call
# stuff I want to test
end
在测试中,您为调用 build_request
提供一个参数:
build_request(TestAPI)
详情请引用此brilliant writing何塞·瓦林 (José Valim) 着。
关于testing - elixir 模拟内部函数 url 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49607976/