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().
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在自己的东西中使用了很多界面,我仍然感到惊讶的是它不属于那里的常见库之一.我有两个实现我用了很多,WallClock和StoppedClock(这是使用一个固定的时间测试有用).