![](/img/trans.png)
[英]Mockito can't mock a property of a third class when I'm testing another one
[英]using mockito to mock the class i'm testing
假设我有一个名为UserController的 controller class ,并且有两种方法: getUserCount()和getLatestUser() ,getUserCount 调用 getLatestUser。
@Controller
class UserController{
public long getUserCount(){
#code
getLatestUser();
#code
}
public User getLatestUser(){}
}
我应该使用 Junit 和 Mockito 测试这些方法中的每一个,因此我有这样的东西:
class UserControllerTest{
@Autowired
UserController userController;
@Test
public void testing_get_user_count(){
User user = new User();
when(userController.getLastestUser()).thenReturn(user);
}
}
我的问题是我不能模拟 UserController,因为我已经自动连接了它,所以我不能在 getLatestUser 上使用 when().thenReturn()。
有没有办法让我嘲笑它?
您可以使用@SpyBean
代替@Autowired
。 它在 bean 上应用 Mockito 间谍。
class UserControllerTest {
@SpyBean
UserController userController;
@Test
public void testing_get_user_count(){
User user = new User();
when(userController.getLastestUser()).thenReturn(user);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.