代码之家  ›  专栏  ›  技术社区  ›  Bitwise

用Mox测试函数链中的多个API调用

  •  1
  • Bitwise  · 技术社区  · 8 年前

    我试图测试我是否正在正确地转换从第三方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端点将被调用两次?

    1 回复  |  直到 8 年前
        1
  •  3
  •   Dogbert    8 年前

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

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