![](/img/trans.png)
[英]How can I mock some method calls of a bean but use the defined bean in other method calls in the same test class?
[英]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 来覆盖一个特殊的错误处理分支。 这可能吗? 有什么我可以使用的方法与@MockBean
的UserBO
吗? ( 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.