【问题标题】:Can I use @MockBean to mock a bean in just one method of my test class?我可以使用@MockBean 在我的测试类的一种方法中模拟一个bean吗?
【发布时间】:2020-12-01 21:08:46
【问题描述】:

我有这个 mvc 测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserTest {

    private MockMvc mockMvc;

    @Resource
    private WebApplicationContext webApplicationContext;

    @MockBean
    private UserBO userBO;

    @Before
    public void init() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
// ...
    }
// ...

在一个测试用例中,我需要模拟另一个 bean 来覆盖一个特殊的错误处理分支。这可能吗?有什么方法我可以使用与UserBO@MockBean 相同的方法吗?PermissionBO 不会被UserBO 重新调整,但在与UserBO 相同的级别上使用测试。)

@Test(expects=IllegalStatusException.class)
public void testErrorHandlingBranch() {
    // How can I mock the bean *PermissionsBO* only for this test?
    // like @MockBean PermissionsBO permissionsBO;
    // Is there a method like injectMockBean(PermissionsBO.class)?
    mockMvc.perform(...)
}

【问题讨论】:

标签: java spring-boot unit-testing mocking


【解决方案1】:

您应该在测试方法中使用thenReturn(),以便仅在特定测试中使用特定的模拟值。

例如: Mockito.when(userBO.example()).thenReturn("Specific test method mock");

【讨论】:

  • 谢谢,但是 PermissionBO 没有从 userBO 返回。我会澄清我的问题。
  • 我不明白你需要做什么。如果PermissionBOUserBO 处于同一级别,那么您可能还需要模拟PermissionBO
  • 谢谢!我完全错了。 PermissionBO 没有理由在这堂课上还没有被完全嘲笑!
猜你喜欢
  • 2014-01-03
  • 2018-12-27
  • 1970-01-01
  • 2018-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
相关资源
最近更新 更多