使用当前时间条件处理单元测试 [英] Handling unit tests with a condition on the current time

查看:406
本文介绍了使用当前时间条件处理单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我正在进行的项目中的某些实用程序类设置单元测试,其中一个类(包含许可信息)有一个方法可以根据当前时间进行一些确定。

I'm taking a stab at setting up unit tests for some utility classes in a project I'm working on, and one of the classes (contains licensing info) has a method that does some determination based on the current time.

ie许可证包含到期日期,许可证字符串验证该日期,但是查看许可证是否过期的实际逻辑基于当前时间。

i.e. the license contains an expiry date, and the license string validates that date, but the actual logic to see if the license is expired is based on the current time.

public boolean isValid()
{
    return isLicenseStringValid() && !isExpired();
}

public boolean isExpired()
{
    Date expiry = getExpiryDate();
    if( expiry == null ) {
        return false;
    }

    Date now = new Date();

    return now.after( expiry );
}

所以,我不知道该做什么,因为'新日期' ()'事情不是一个静态的标准。

So, I'm not sure what to do, since the 'new Date()' thing isn't a static criterion.


  1. 我不应该费心去测试'isValid',只测试'isLicenseStringValid() '和'getExpiryDate()'功能分开?

  2. 我是否只是在测试中使用许可证密钥,并且到期时间很长,这样我就可以在到期时切换作业?

  3. 我是否尝试将'new Date()'模拟为某些'getCurrentTime()'方法,以便我可以伪造它现在的时间?

其他人通常对时间条件的测试做些什么?

What do others normally do with tests that are time-conditional?

推荐答案

绝对模拟新日期()

创建时钟接口与 getCurrentTime()方法或类似的东西。这样你可以有一个 FakeClock 进行测试, SystemClock 使用 System.currentTimeMillis( )或其他什么。

Create a Clock interface with a getCurrentTime() method or something similar. That way you can have a FakeClock for testing and a SystemClock which uses System.currentTimeMillis() or whatever.

我已经多次这样做了 - 它运作得非常好。这也是合乎逻辑的 - 实际上你需要一个当前时间服务,因此应该像任何其他依赖项一样注入。

I've done this a number of times - it's worked extremely well. It's logical too - effectively you require a "current time service" so that should be injected like any other dependency.

这篇关于使用当前时间条件处理单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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