【问题标题】:using mockito to mock the class i'm testing使用 mockito 来模拟我正在测试的课程
【发布时间】:2022-01-04 16:28:12
【问题描述】:

假设我有一个名为 UserController 的控制器类,它有 2 个方法: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()。

有没有办法让我模拟它?

【问题讨论】:

  • 改为@Spy
  • 我建议遵循关于如何在春季模拟和测试 bean 的指南。

标签: java spring unit-testing junit mockito


【解决方案1】:

您可以使用@SpyBean 代替@Autowired。它在 bean 上应用 Mockito spy。

class UserControllerTest {
  @SpyBean
  UserController userController;

  @Test
  public void testing_get_user_count(){
    User user = new User();
    when(userController.getLastestUser()).thenReturn(user);
  }
}

【讨论】:

  • 是的,这似乎是我能找到的最好的解决方案,谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多