我怎么能模仿JodaTime的实际约会?

Adr*_*cha 22 java testing mocking jodatime

我想测试这个方法:

 public FirmOrder findActiveByModelColor(ModelColor modelColor) {
   Query query = em.createQuery("FROM FirmOrder fo WHERE fo.modelColor = :modelColor AND fo.year = :year AND fo.month = :month");
   query.setParameter("modelColor", modelColor);
   query.setParameter("year", new DateTime().year().get());
   query.setParameter("month", new DateTime().monthOfYear().get());
   return (FirmOrder) query.getSingleResult();
 }
Run Code Online (Sandbox Code Playgroud)

但我需要DateTime().year().get()DateTime().dayOfMonth().get()始终返回相同的日期

TKS

axt*_*avt 53

如果您无法按照skaffman的建议添加工厂对象,则可以使用DateTimeUtils.setCurrentMillisFixed().

  • 评论很好,我想要两次. (7认同)
  • 此API修改全局变量,因此必须避免. (6认同)
  • 也许你想在测试断言后用`setCurrentMillisSystem`将它重置回系统. (5认同)

ska*_*man 15

然后,您需要定义一个Clock接口,并将其注入您的类

public interface Clock {
    DateTime getCurrentDateTime();
}
Run Code Online (Sandbox Code Playgroud)

然后:

Clock clock;

public FirmOrder findActiveByModelColor(ModelColor modelColor) {
   Query query = em.createQuery("FROM FirmOrder fo WHERE fo.modelColor = :modelColor AND fo.year = :year AND fo.month = :month");
   query.setParameter("modelColor", modelColor);
   query.setParameter("year", clock.getCurrentDateTime().year().get());
   query.setParameter("month", clock.getCurrentDateTime().dayOfMonth().get());
   return (FirmOrder) query.getSingleResult();
 }
Run Code Online (Sandbox Code Playgroud)

然后,您的测试可以注入Clock始终返回固定时间的实现(例如,使用模拟框架).

Clock在自己的东西中使用了很多界面,我仍然感到惊讶的是它不属于那里的常见库之一.我有两个实现我用了很多,WallClockStoppedClock(这是使用一个固定的时间测试有用).