【问题标题】:Mock test method with the return value带返回值的模拟测试方法
【发布时间】:2019-01-11 15:42:59
【问题描述】:

如何为具有返回值的方法(类实例)编写模拟测试

用户服务

public User getUserInfo(String userId) {
        RestTemplate restTemplate = new RestTemplate();
        String url = http:127.0.0.1 + userId ;
        return restTemplate.getForObject(url, User.class);
}

public class TimUser {
    private String id = null;
    private String userName = null;
    **********GET & SET method***********;
}

 @Mock
private userService userService;
private String userId;


@Before
public void set_up(){
    MockitoAnnotations.initMocks(this);
    userId = "";
}

@Test
public void getUserInfo(){

    userService.getUserInfo(userId)

}

这种方法我不知道怎么写测试用例,谁能提供一些想法?

【问题讨论】:

  • 也许我不太了解这个问题,但从我所见,您似乎正在尝试测试您的模拟?事实上,我不明白为什么你需要一个模拟,因为 getUserInfo() 方法的结果似乎只取决于输入。
  • 你不要模拟你正在测试的课程。我认为您需要在您的用户服务上使用@InjectMocks 并模拟restTemplate。

标签: java spring-boot mockito


【解决方案1】:
Mockito.when(userService.getUserInfo(userId)).thenReturn(value);

虽然不完全确定您要在这里实现什么。如果您正在测试的类是 UserService,那么您不应该嘲笑它。您应该在测试中调用 getUserInfo 并断言返回值与您的预期相同。

【讨论】:

    【解决方案2】:

    你可以在 mockito 中使用 when(mock.method).thenReturn(value)。

    when(userservice.getUserInfo(eq(this.userId)).thenReturn(<your value here>)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-01
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-09
      相关资源
      最近更新 更多