java - 我可以使用@MockBean 在我的测试类的一种方法中模拟一个bean吗?
问题描述
我有这个 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
不被重新调整,但在与被测类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");
推荐阅读
- java - 每月和每周将日期设置为Java中的特定日期
- android - 以编程方式连接到它时 Wifi Internet 无法正常工作 android>=10
- mysql - 按unix时间戳选择数据
- java - 带有 Firefox 的 Selenium 没有单击使用 XPath 定位的元素
- python - 使用 matplotlib 绘制带有颜色条的 RTI 图
- javascript - 如何让这个元素向后移动?
- python - Python max(list) 打印低于 10 的最大值
- python - 如何使用 pythons smtplib 模块设置本地 SMTP 服务器以发送邮件
- django - django 休息:@api_view 和 @classmethod 错误
- dialogflow-cx - 有没有办法在 DialogFlow CX 中使用或集成外部 NLU 引擎?