【发布时间】:2018-08-12 11:14:27
【问题描述】:
我正在为我的 Spring 启动应用程序使用 cucumber 编写功能测试。我要测试的逻辑使用当前时间,基于结果不同。有没有办法在功能测试中模拟当前时间
【问题讨论】:
-
是的,有一些方法可以模拟当前时间。您可能应该分享您用于检索当前时间的内容。
标签: spring-boot mocking cucumber functional-testing
我正在为我的 Spring 启动应用程序使用 cucumber 编写功能测试。我要测试的逻辑使用当前时间,基于结果不同。有没有办法在功能测试中模拟当前时间
【问题讨论】:
标签: spring-boot mocking cucumber functional-testing
这可以使用 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);
}
}
【讨论】: