我一直在尝试找出一种方法来测试以下代码(在 Elixir 中):
defmacro __using__(_) do
quote do
# API functions will be used from this client
import Client.API
def list_storages do
case list_buckets do
{:ok, res} ->
case res.status_code do
200 ->
res.body
|> Friendly.find("name")
|> Enum.map(fn bucket -> bucket.text end)
_ ->
res |> show_error_message_and_code
end
{:error, reason} ->
parse_http_error reason
end
end
...
问题是 list_buckets
函数正在从 Client.API
模块中导入(已经在另一个项目中进行了测试,我无法在那里真正改变任何东西) .我的想法是对 API 函数进行 stub/mock/dummy,以便它们只返回一个虚拟回复。我已经尝试使用 defoverridable
覆盖 list_buckets
函数,但这不起作用,因为函数定义发生在另一个模块中。
我已阅读以下内容 post由 José Valim 编写,这有助于测试 Client.API 模块,但我找不到将这些概念应用到这个特定问题的方法。
到目前为止,我唯一(也是愚蠢)的想法是在测试文件中重新实现宏内的每个函数,并使用在那里定义的虚拟 API 函数,但如果在非测试代码。
基本上我想测试三种可能的情况是否正确:
- 接收
{:ok, res}
和代码200
-> 输出正确的数据 - 接收
{:ok, res}
和另一个code -> 输出错误信息和code - 接收
{:error,reason}
-> 解析HTTP错误并输出失败原因
谁能帮我解决这个问题?
最佳答案
您仍然可以使用该博文中的原则。不要导入 Client.Api
,而是将其作为最后一个变量传递给 list_storages
。
def list_storages(api \\ Client.Api) do
case api.list_buckets do
这样您就不需要更改应用程序代码中的任何内容,并且可以在测试函数时传递虚拟模拟。
关于testing - 如何测试使用从另一个模块导入的客户端 API 函数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37091145/