![](/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.