我正在尝试测试我是否正确地转换了从第三方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端点将被调用两次呢?
发布于 2018-08-03 23:52:42
third optional argument to expect是模拟函数应该被调用的次数。在本例中,只需将其设置为2
Statcasters.SportRadarNbaApi.ClientMock
|> expect(:team_profile, 2, fn _ ->
{:ok, team_profile_map()}
end)https://stackoverflow.com/questions/51675892
复制相似问题