spring-boot - 模拟功能测试的当前时间
问题描述
我正在为我的 Spring 引导应用程序使用 cucumber 编写功能测试。我要测试的逻辑使用当前时间,基于结果不同。有没有办法在功能测试中模拟当前时间
解决方案
这可以使用 PowerMock http://powermock.github.io/
@RunWith(PowerMockRunner.class)
// ... other annotations
public class SomeTest {
private final Date fixedDate = new Date(10000);
@Before
public void setUp() throws Exception {
PowerMockito.whenNew(Date.class).withNoArguments().thenReturn(fixedDate);
}
...
}
另一种方法是使用一些提供当前时间的服务并在测试中模拟该服务。粗略的例子
@Service
public class DateProvider {
public Date current() { return new Date(); }
}
@Service
public class CurrentDateConsumer {
@Autowired DateProvider dateProvider;
public void doSomeBusiness() {
Date current = dateProvider.current();
// ... use current date
}
}
@RunWith(Cucumber.class)
public class CurrentDateConsumerTest {
private final Date fixedDate = new Date(10000);
@Mock DateProvider dateProvider;
@Before
public void setUp() throws Exception {
when(dateProvider.current()).thenReturn(fixedDate);
}
}
推荐阅读
- python - Python Beautifulsoup 无法获取 svg 标签
- python - 使用带有 SSL 的 sqlalchemy 和 pg8000 连接到数据库的正确方法是什么?
- javascript - 在python中执行Javascript的语法
- typescript - 扩展多个接口的更好方法
- java - 在 Junit 5 中使用 Mockito 静态模拟时如何抛出 InterruptedException?
- apache - 子域HTTP和HTTPS去不同的目录,Apache2.4
- python - 如何将matplotlib图形转换为二进制类型
- python-3.x - 如何修复“列表索引超出范围错误”
- python - 在索引页上将数据从 c# 打印到烧瓶
- android - 如何在 Chrome、Android 上的 Video.js 中设置 HLS (m3u8) 的初始时间