testing - 如何测试使用从另一个模块导入的客户端 API 函数的函数?

标签 testing elixir web-api-testing

我一直在尝试找出一种方法来测试以下代码(在 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 函数,但如果在非测试代码。

基本上我想测试三种可能的情况是否正确:

  1. 接收 {:ok, res} 和代码 200 -> 输出正确的数据
  2. 接收{:ok, res}和另一个code -> 输出错误信息和code
  3. 接收{: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/

相关文章:

java - Karate - 有什么方法可以获取当前功能文件的名称

json - 在 SOAPUI 中编辑传输的对象(使用属性传输)

java - 使用 Web 界面或任何可视化工具运行 Selenium WebDriver 测试

c# - Selenium 在 C# 中的显式等待用法

perl - 我如何在 Perl 中进行单元测试?

ruby - 绑定(bind)与分配

ruby-on-rails - Phoenix 中 Rails 的 before_filter 等价物

web-api-testing - SwaggerHub的替代品

使用 Robolectric ClassCastException : android. app.Application 进行的 Android 测试无法转换为 MyApplication

Elixir 混合格式忽略行长选项