Testing elixir模拟内部函数url请求
我如何模拟特定的api调用,类似于python请求模拟的工作方式:Testing elixir模拟内部函数url请求,testing,mocking,elixir,Testing,Mocking,Elixir,我如何模拟特定的api调用,类似于python请求模拟的工作方式: with requests_mock.mock() as m: m.get('http://test.com', text='data') requests.get('http://test.com').text 在本例中,每次调用http://test.comwith语句内部将被模拟 例如,在长生不老药中,我有: defmodule API do # makes a call to an externa
with requests_mock.mock() as m:
m.get('http://test.com', text='data')
requests.get('http://test.com').text
在本例中,每次调用http://test.com
with语句内部将被模拟
例如,在长生不老药中,我有:
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\u request
mockingmake\u call
我尝试了这个包,但是这个包的作用是用一个mock formake_call
方法覆盖整个API模块,但是你也会丢失API模块的所有其他函数,我不希望这样
我怎么能嘲笑那个电话
这里是我看到的另一个例子
但这是同一个问题,它在测试中直接模拟请求,我的问题是当模拟需要在内部函数中进行时,而不是立即进行。是您的朋友:
def build_request(caller \\ API) do
caller.make_call
# stuff I want to test
end
在测试中,您向调用生成请求
提供一个参数:
build_request(TestAPI)
有关详细信息,请参阅JoséValim的文章。当您可以使用DI时,这很好,但是如果您依赖BIF产生的副作用(OTP应用程序入口点的start/2功能中的设置就是一个很好的例子),该怎么办?@Charlie我不确定我是否遵循了。你能提供一个例子吗?
defstart(_type,_args)do start_link([],[strategy::one_for_one,name::root])end
我的意思是,也许我在测试这个时尝试做的是错误的,实际上,我想我可以运行这个函数,只测试依赖关系树中是否存在命名的进程。但是如果我真的想监视start_link/2,我的选择是什么呢?我怀疑我是否理解测试def foo(),do:bar()
的目的确实调用bar()
(如果没有,没有任何效果),但是依赖注入仍然是你最好的朋友:为测试声明一个专用子句def start(\u type,mock:true),执行:Test.start_link())
并在那里测试您想要的任何内容。
build_request(TestAPI)