問題描述
我正在嘗試為我正在處理的項目中的一些實用程序類設置單元測試,其中一個類(包含許可信息)具有一種基于當前時間進行某些確定的方法.
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.
- 我是否應該不費心去測試 'isValid',而只測試 'isLicenseStringValid()' 和 'getExpiryDate()' 函數?
- 我是否只是在測試中使用過期時間很長的許可證密鑰,這樣我就可以在過期時換工作?
- 我是否嘗試將 '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.
這篇關于處理具有當前時間條件的單元測試的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!