繁体   English   中英

我可以在我的测试 class 的一种方法中使用 @MockBean 来模拟 bean 吗?

[英]Can I use @MockBean to mock a bean in just one method of my test class?

我有这个 mvc 测试 class

@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中的 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(...)
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM