[英]using mockito to mock the class i'm testing
Let's say i have a controller class called UserController , and withing it there are 2 methods: getUserCount() and getLatestUser() , and getUserCount calls getLatestUser.假设我有一个名为UserController的 controller class ,并且有两种方法: getUserCount()和getLatestUser() ,getUserCount 调用 getLatestUser。
@Controller
class UserController{
public long getUserCount(){
#code
getLatestUser();
#code
}
public User getLatestUser(){}
}
i'm supposed to test each of these methods using Junit and Mockito, and thus i have something like this:我应该使用 Junit 和 Mockito 测试这些方法中的每一个,因此我有这样的东西:
class UserControllerTest{
@Autowired
UserController userController;
@Test
public void testing_get_user_count(){
User user = new User();
when(userController.getLastestUser()).thenReturn(user);
}
}
My issue is that i can't mock UserController because i've autowired it, so i can't use when().thenReturn() on getLatestUser.我的问题是我不能模拟 UserController,因为我已经自动连接了它,所以我不能在 getLatestUser 上使用 when().thenReturn()。
Is there a way for me to mock it anyways?有没有办法让我嘲笑它?
You can use @SpyBean
instead of @Autowired
.您可以使用@SpyBean
代替@Autowired
。 It applies Mockito spy on a bean.它在 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.