【问题标题】:Testing multiple API calls in a function chain with Mox使用 Mox 测试函数链中的多个 API 调用
【发布时间】:2018-08-03 15:30:19
【问题描述】:

我正在尝试测试我是否正确转换了从第三方 api 返回的数据。我在使用 Mox 时遇到了一些麻烦,因为我需要在数据转换期间访问两个单独的端点。让我通过发布代码更清楚地解释:

测试:

  test "players/0 return all active players" do
    Statcasters.SportRadarNbaApi.ClientMock
    |> expect(:league_hierarchy, fn ->
      {:ok, league_hierarchy_map()}
    end)

    Statcasters.SportRadarNbaApi.ClientMock
    |> expect(:team_profile, fn _ ->
      {:ok, team_profile_map()}
    end)


    assert Statcasters.Sports.Nba.get_players() == ["Kevon Looney", "Patrick McCaw"]
  end

代码:

  def get_players do
    with {:ok, hierarchy} <- @sport_radar_nba_api.league_hierarchy,
         team_ids <- get_team_ids(hierarchy),
         players <- get_team_players(team_ids)
    do
      IO.inspect players
    end
  end

  defp get_team_players(team_ids) do
    for team_id <- team_ids do
      {:ok, team} = @sport_radar_nba_api.team_profile(team_id)
    end
  end

忽略编写的代码实际上不会通过测试的事实。这是我试图弄清楚的测试失败。

问题:

第二个 api 调用 team_profile 在测试中被调用了两次,因为我遍历了两个 team_ids 并且对于每个 team_id 我调用了 API。这是意料之中的,但测试并没有为此做好准备,因为我收到了这个错误。

错误:

** (Mox.UnexpectedCallError) expected Statcasters.SportRadarNbaApi.ClientMock.team_profile/1 to be called once but it has been called 2 times in process #PID<0.410.0>

这是正确的。我确实调用了两次,但是如何设置测试以期望该 API 端点将被调用两次?

【问题讨论】:

    标签: elixir mox


    【解决方案1】:

    third optional argument to expect 是模拟函数应该被调用的次数。在这种情况下,只需将其设置为2

    Statcasters.SportRadarNbaApi.ClientMock
    |> expect(:team_profile, 2, fn _ ->
      {:ok, team_profile_map()}
    end)
    

    【讨论】:

    • 那是布里尔!另外,我不知道我是怎么错过的。一如既往地感谢@Dogbert
    猜你喜欢
    • 1970-01-01
    • 2022-01-19
    • 2022-01-26
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多