首页 > 解决方案 > 我可以使用@MockBean 在我的测试类的一种方法中模拟一个bean吗?

问题描述

我有这个 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 来覆盖一个特殊的错误处理分支。这可能吗?有什么我可以使用的方法@MockBeanUserBO? 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(...)
}

标签: javaspring-bootunit-testingmocking

解决方案


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

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


推荐阅读