Junit 与 new Date()
当我有以下方法时,junit 测试会是什么:
@Override
public void saveLastSuccesfullLogin(final User user) {
gebruiker.setLastLogin(new Date());
storeUser(user);
}
子方法 storeUser:
@Override
public void storeUser(final User user) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.merge(user);
em.getTransaction().commit();
em.close();
}
我遇到的问题是为实体用户设置然后存储的日期。我使用 junit 和 easymock。
What would the junit test be when i have the following method:
@Override
public void saveLastSuccesfullLogin(final User user) {
gebruiker.setLastLogin(new Date());
storeUser(user);
}
submethode storeUser:
@Override
public void storeUser(final User user) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.merge(user);
em.getTransaction().commit();
em.close();
}
The problem i have is the date, being set for the entity user and then stored. Im using junit and easymock.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试将 new Date() 拉入具有默认访问说明符的方法中,如下所示
在您的测试类中使用模拟或存根日期覆盖该类,如下所示。
通过这种方式,您可以轻松断言日期值,因为它将被删除。
Try pulling the new Date() into a method with default access specifier like below
In your test class override the class as below using a mock or stubbed date.
In this way you can assert the date value easily as it is going to be stubbed out.
日期有什么问题?你不知道稍后断言是什么?一些替代方案:
What's the problem with the Date? That you don't know what it is to assert later? A few alternatives:
还有一种更“企业”的方法可以在依赖注入可用的情况下使用(例如在 EJB、Spring 等中)。
您可以定义一个接口(例如 TimeService)并添加返回当前日期的方法。
您可以实现此方法以返回
new Date()
并按如下方式使用它:这显然非常容易测试,因为您可以模拟
TimeService
。使用 EasyMock(仅是一个示例),这可能是:在整个代码中使用
TimeService
并且从不使用new Date()
是一个非常好的实践,并且具有其他优点,例如出色地。我发现它在很多情况下都很有用,包括对将来激活的功能进行手动功能测试。更进一步,可以从外部系统检索系统时间,从而使其在集群等之间保持一致。There is also a more "enterprise" approach that may be used where Dependency Injection is available (like in EJB, Spring etc.).
You can define an interface, for example TimeService and add e method that returns the current date.
You can implement this to return
new Date()
and use it like this:This will obviously be very easy to test because you can mock the
TimeService
. Using EasyMock (just an example), this might be:Using the
TimeService
throughout the entire code and never usingnew Date()
is a pretty good practice and has other advantages as well. I found it helpful in a number of occasions, including manual functional testing of features that would activate in the future. Going even further, the system time may be retrieved from an external system thus making it consistent across clusters etc.您还可以创建一个 getDate 方法和一个日期静态变量:
然后在您的测试方法中,您可以继续调用 setDate 来控制您将获得的日期。
You can also create a getDate method, and a date static var:
Then in your test method, you can go ahead and call setDate to control what date you will get.