java - Overriding spring @Configuration in an integration test
问题描述
I have a spring boot configuration class like this:
@Configuration
public class ClockConfiguration {
@Bean
public Clock getSystemClock() {
return Clock.systemUTC();
}
}
and I have some integration tests like this:
@SpringBootTest(classes = MyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public abstract class AbstractIntegrationTest {
}
and tests like this:
public class MiscTests extends AbstractIntegrationTest{
@Test
public void CreateSomethingThatOnlyWorksInThe Morning_ExpectCorrectResponse() {
}
I want to be able to offset the clock bean to run some tests at different times on the day. How do I do this?
NOTE: I see several stack overflow answers similar to this, but I can't get them to work.
Based on other responses, it appears the solution should be something like:
@SpringBootTest(classes = MyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public abstract class AbstractIntegrationTest {
@Configuration
class MyTestConfiguration {
@Bean
public Clock getSystemClock() {
Clock realClock = Clock.systemDefaultZone();
return Clock.offset(realClock, Duration.ofHours(9));
}
}
}
But nothing happens there. Do I need to @Import something? do I need to @Autowired something?
Thanks!
解决方案
当您使用 Spring Boot 时,您可以利用@MockBean
注释:
@SpringBootTest(classes = MyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public abstract class AbstractIntegrationTest {
@MockBean
private Clock clockMock;
}
然后,您可以相应且唯一地存根该 bean 的公共方法和每个测试:
@Test
public void CreateSomethingThatOnlyWorksInThe Morning_ExpectCorrectResponse() {
when(clockMock.getTime()).thenReturn(..);
}
根据 javadoc 的@MockBean
:
在上下文中定义的任何现有的相同类型的单个 bean 都将被模拟替换。
推荐阅读
- json - 写入 bzip2 存档
- php - PHP - 从句子中删除特定单词
- python - 如何使用 Telethon 向我的频道发送消息
- dbt - 自定义模式名称的宏不适用于 dbt 包
- ruby-on-rails - 是否可以使用与 form_for 相同的参数范围,除了 AJAX 调用?
- node.js - 带有 mern 堆栈的 socket.io 无法对未安装的组件执行 React 状态更新
- javascript - JS上页面加载数据的问题
- android - “KOTLIN”将 PDF 保存到 Media.Downloads 创建 0 字节的 pdf
- discord.js - 您将如何仅通过用户获得对 dm 频道的引用?
- python-3.x - 如何创建一个upload_to 文件夹,该文件夹被命名为属于同时创建的模型的字段?