在JUnit测试夹具中设置时间和日期 [英] Setting time and date in JUnit test fixture

查看:196
本文介绍了在JUnit测试夹具中设置时间和日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为Java代码的一部分,明天需要在JUnit中完成一些任务。

As part of Java code some task needs to be done tomorrow in JUnit.

例如,有3个任务:


  • task1 - 完成

  • task2 - 明天再做

  • task3 - 然后就会发生
  • li>
  • task1 - done
  • task2 - do it tomorrow
  • task3 - then this will happen

因此,根据要求,我需要在Java中设置今天的日期。

So as per requirement I need to set today's date as tomorrow in Java.

推荐答案

你的问题的根源是系统时钟(在新的日期()中给你时间的东西)没有给出您需要进行测试的时间。

The root of your problem is that the system clock (what gives you the time in a new Date ()) is not giving you the time you need for your test.

您可以通过引入一个间接级别来避免此问题。您没有让代码直接询问Java API当前时间,而是让您的代码询问 Clock 对象的时间。在实际程序中, Clock 实现使用系统时钟。对于您的单元测试,您使用 FakeClock ,它表示您想要的任何时间。您告诉您的代码使用依赖注入来使用 Clock 。您必须自己编写 Clock 接口(或抽象基类)及其具体实现。

You can avoid this problem by introducing a level of indirection. Instead of having your code directly ask the Java API what the current time is, you have your code ask a Clock object what the time is. In the real program your Clock implementation uses the system clock. For your unit tests you use a FakeClock, which says whatever time you want it to. You tell your code what Clock to use using dependency injection. You have to write the Clock interface (or abstract base class) and its concrete implementations yourself.

此方法需要您可以更改现有代码,因此更容易测试或首先编写代码,因此更容易测试。这是单元测试的一个技巧。

This approach requires you to alter your existing code, so it is easier to test, or write it in the first place so it is easier to test. It's one of the tricks of unit testing.

我正在研究一些时间敏感的代码。我的时钟接口只是

I'm working on some code at the moment that is time sensitive. My clock interface is simply

 public interface Clock {
    long getCurrentTime ();
 }

这篇关于在JUnit测试夹具中设置时间和日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆