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

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

问题描述

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

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

例如有 3 个任务:

  • task1 - 完成
  • task2 - 明天做
  • task3 - 那么这会发生

因此,根据要求,我需要在 Java 中将今天的日期设置为明天.

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

推荐答案

您问题的根源在于系统时钟(在 new Date () 中为您提供的时间)没有给出考试所需的时间.

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天全站免登陆