spring - MockBean 存根无效
问题描述
我有一个配置类,其中一些 MockBeans 替换了上下文中的实际 bean 以进行测试。
@Configuration
public class MyTestConfig {
@MockBean
private MyService myService;
}
我在测试中使用这些模拟:
@Import({ MyTestConfig .class })
public class MyTest {
@Autowired
private MyService myService;
@Test
public void aTest() {
...
}
}
首先的想法是在这个MyTestConfig
配置类中添加存根,以便为所有测试预先制作模拟,所以我在一个@PostConstruct
方法中做了它,它工作得很好 - 测试中的模拟确实返回了预期值:
@PostConstruct
public void init() {
when(myService.foo("say hello")).thenReturn("Hello world");
}
但事实证明,构建一个适合所有测试的预制模拟可能很棘手,因此我们决定将存根转移到测试中。
@Test
public void aTest() {
when(myService.foo("say hello")).thenReturn("Hello world");
}
这不起作用 - 存根方法返回null
。我们想将 MockBeans 留在配置类中,但在测试中对它们进行存根,那么关于为什么存根无效的任何建议?
Spring Boot 2.0.5,Mockito 2.22.0
解决方案
是的,应该在各自的测试用例中执行存根(除非您有一个共享存根场景的测试类,但这一切都归结为偏好)。
但是,对于创建@MockBeans
,您需要使用 a@SpringBootTest
来将实际的 bean 替换为模拟。这可以像这个例子一样简单地完成:
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {
@Autowired
private MyTestClass testClass;
@MockBean
private MyService service;
@Test
public void myTest() {
// testing....
}
}
推荐阅读
- c# - 在 ASP.NET Core 的视图中登录用户名
- rust - 管理同一段内存的多个切片
- java - 仅在其他方法完成时调用方法 - RxJava
- wordpress - 古腾堡向编辑器添加富文本按钮,按钮不出现
- c++ - 调用 std::unique_ptr 指向的底层对象的 operator()
- php - WooCommerce - 如果单个产品页面上的产品类别声明
- amazon-web-services - 使用自定义客户端 ID 时连接超时
- minecraft - 为什么我的 mod 中没有调用 registerSounds?
- javascript - 使用搜索词过滤 json 数组
- python - 仅当我将“D”作为密码传递时,Python 才会抛出“zipfile.BadZipFile: Bad CRC-32”