Java 我可以使用@MockBean在测试类的一个方法中模拟bean吗?
我有一门mvc测试课Java 我可以使用@MockBean在测试类的一个方法中模拟bean吗?,java,spring-boot,unit-testing,mocking,Java,Spring Boot,Unit Testing,Mocking,我有一门mvc测试课 @RunWith(SpringRunner.class) @SpringBootTest public class UserTest { private MockMvc mockMvc; @Resource private WebApplicationContext webApplicationContext; @MockBean private UserBO userBO; @Before public vo
@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
相同的级别上使用。)
您应该在测试方法中使用
thenReturn()
,以便仅在特定测试中使用特定模拟值
例如:
Mockito.when(userBO.example()).thenReturn(“特定测试方法模拟”)
您可能应该在全局范围内尝试使用然后调用realmethod
,并在这一测试中实际模拟该方法。在这里阅读更多:谢谢,但是许可证不是从userBO返回的。我会澄清我的问题。我不知道你到底需要做什么。如果PermissionBO
与UserBO
处于同一级别,您可能还需要模拟PermissionBO
。谢谢!我完全错了。在这个类中,PermissionBO
没有被完全模仿的理由!
@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(...)
}