处理具有当前时间条件的单元测试

Handling unit tests with a condition on the current time(处理具有当前时间条件的单元测试)
本文介绍了处理具有当前时间条件的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试为我正在处理的项目中的一些实用程序类设置单元测试,其中一个类(包含许可信息)具有一种基于当前时间进行某些确定的方法.

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.

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

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 );
}

所以,我不确定该怎么做,因为new Date()"不是静态标准.

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?

推荐答案

一定要mock out new Date().

Definitely mock out new Date().

使用 getCurrentTime() 方法或类似方法创建一个 Clock 接口.这样你就可以有一个 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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Show progress during FTP file upload in a java applet(在 Java 小程序中显示 FTP 文件上传期间的进度)
How to copy a file on the FTP server to a directory on the same server in Java?(java - 如何将FTP服务器上的文件复制到Java中同一服务器上的目录?)
FTP zip upload is corrupted sometimes(FTP zip 上传有时会损坏)
Enable logging in Apache Commons Net for FTP protocol(在 Apache Commons Net 中为 FTP 协议启用日志记录)
Checking file existence on FTP server(检查 FTP 服务器上的文件是否存在)
FtpClient storeFile always return False(FtpClient storeFile 总是返回 False)