首页 > 解决方案 > 模拟功能测试的当前时间

问题描述

我正在为我的 Spring 引导应用程序使用 cucumber 编写功能测试。我要测试的逻辑使用当前时间,基于结果不同。有没有办法在功能测试中模拟当前时间

标签: spring-bootmockingcucumberfunctional-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);
   }
}

推荐阅读