【发布时间】: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(...)
}
【问题讨论】:
-
您可能应该在全局范围内尝试使用
thenCallRealMethod,并在这一测试中实际模拟该方法。在这里阅读更多:javadoc.io/static/org.mockito/mockito-core/3.4.6/org/mockito/…
标签: java spring-boot unit-testing mocking