代码之家  ›  专栏  ›  技术社区  ›  Datz

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

  •  0
  • Datz  · 技术社区  · 4 年前

    我有一个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来覆盖一个特殊的错误处理分支。这可能吗?我能用什么方法来做同样的事情吗 @MockBean 对于 UserBO ? ( PermissionBO 未被重新调整 用户BO 但使用水平与 用户BO 在受测班级中。)

    @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(...)
    }
    
    0 回复  |  直到 4 年前
        1
  •  -2
  •   liviubiur    4 年前

    你应该使用 thenReturn() 在测试方法中,只在特定测试中使用特定的模拟值。

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