【问题标题】:Mocking current time for functional tests模拟功能测试的当前时间
【发布时间】:2018-08-12 11:14:27
【问题描述】:

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

【问题讨论】:

  • 是的,有一些方法可以模拟当前时间。您可能应该分享您用于检索当前时间的内容。

标签: spring-boot mocking cucumber functional-testing


【解决方案1】:

这可以使用 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);
   }
}

【讨论】:

  • 当我在黄瓜中进行功能测试时,这将不可用
  • @Priya,似乎。我已经更新了我的答案以获得更通用的解决方案
猜你喜欢
  • 1970-01-01
  • 2015-10-21
  • 2011-05-25
  • 2020-03-27
  • 1970-01-01
  • 2019-12-10
  • 2017-10-27
  • 1970-01-01
  • 2021-10-13
相关资源
最近更新 更多