使用 mockito 模拟我正在测试的 class

using mockito to mock the class i'm testing

假设我有一个名为 UserController 的控制器 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);
  }
}