Junit Mock重复了伪客户呼叫,但只有最后一个Mock被多次返回

问题描述 投票:0回答:1

我有一个Spring Boot应用程序,当创建新部门时(新部门将插入Department表中),该应用程序使用Feign Client调用微服务将用户添加到User表中。该请求看起来像:

请求:

 {
  "department": "math",
  "usernameList": ["aaa", "bbb", "ccc"]
 }

用户模型:

 public class User {
    private String username;
 }

假客户:

 import org.springframework.cloud.openfeign.FeignClient;
 @FeignClient(name = "user-client", url = "/.../user", configuration = UserConfiguration.class)

 public interface UserClient {

     @RequestMapping(method = RequestMethod.POST, value = "users")
     User createUser(User user);
 }

UserService:

@Service
public class UserService {

private final UserClient userClient;       

public UserResponse createUser(@Valid Request request);

     List<User> userList = request.getUsernameList()
           .stream()
           .map(username -> userClient.createUser(mapToUser(username)) 
           .collect(Collectors.toList());
 ......
}

以上代码有效,我能够将3个用户添加到数据库中。 userList具有3个正确的用户名。但是,当我在下面运行junit测试时,似乎只有最后一个userResp(“ ccc”)作为模拟响应返回了3次。当我在调试模式下运行junit测试时,我看到每次thenReturn(userResp)都有正确的userResp,但是在UserService中,userList最终包含3个“ ccc”,而不是“ aaa,bbb, ccc”。我尝试在UserService中而不是流中使用FOR循环,结果是相同的,所以不是因为流。我还尝试删除Junit中的FOR循环,并仅调用了3次模拟,结果相同。我不确定这是否与Feign客户端模拟有关,或者我在测试用例中做错了什么。有人可以帮忙吗?

我的Junit:

 public class UserTest {

    @MockBean
    private UserClient userClient;  

    @Test
    public void testAddUser() throws Exception {

        for (int i=1; i<=3; i++) {

             User userResp = new User();

              if (i==1) {
             userResp.setUsername("aaa");
            // mock response
       Mockito.when(userClient.createUser(ArgumentMatchers.any(User.class)))
         .thenReturn(userResp);
           }
           if (i==2) {
             userResp.setUsername("bbb");
            // mock response
       Mockito.when(userClient.createUser(ArgumentMatchers.any(User.class)))
         .thenReturn(userResp);
           }
        if (i==3) {
             userResp.setUsername("ccc");
            // mock response
       Mockito.when(userClient.createUser(ArgumentMatchers.any(User.class)))
         .thenReturn(userResp);
           }
       }

       // invoke the real url
       MvcResult result = mockMvc.perform(post("/users")
            .content(TestUtils.toJson(userRequest, false))
            .contentType(contentType))
            .andDo(print())
            .andExpect(status().isCreated())
            .andReturn();  
    }
spring-boot junit spring-cloud-feign
1个回答
0
投票
要使方法为以后的调用返回不同的值,可以使用

Mockito.when(userClient.createUser(ArgumentMatchers.any(User.class))) .thenReturn("aaa") .thenReturn("bbb") .thenReturn("ccc"); //any

© www.soinside.com 2019 - 2024. All rights reserved.