我正在为我的Spring Boot应用程序编写一个使用Cucumber的功能测试。我要测试的逻辑使用当前时间,但结果会有所不同。有没有一种方法可以模拟功能测试中的当前时间
答案 0 :(得分:0)
使用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);
}
}