![](/img/trans.png)
[英]How do I write unit tests to make sure my date/time based code works for all time zones and with/out DST?
[英]Make unit tests with dates pass in all time zones and with/out DST
無論 DST 是否處於活動狀態,如何使此單元測試在所有時區都通過?
import static org.junit.Assert.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.joda.time.DateTime;
import org.junit.Test;
public class TimeZoneTest {
private final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat( "yyyy.MM.dd'T'HH:mm.ss:SSSZZ" );
@Test
public void testUtilDateMillis() throws Exception {
assertEquals( "1970.01.01T00:00.00:000+0000", DATE_FORMAT.format( new Date( 0L ) ) );
}
@Test
public void testDateTimeMillis() throws Exception {
assertEquals( "1970-01-01T00:00:00.000+00:00", new DateTime( 0L ).toString() );
}
}
默認情況下,新的SimpleDateFormat
將使用系統默認時區。 如果需要特定的時區,則應在其上調用setTimeZone
:
private final static SimpleDateFormat DATE_FORMAT = createFormat();
private static SimpleDateFormat createFormat() {
// Make sure there are no locale-specific nasties, either...
SimpleDateFormat ret = new SimpleDateFormat("yyyy.MM.dd'T'HH:mm.ss:SSSZZ",
Locale.US);
ret.setTimeZone(TimeZone.getTimeZone("Etc/UTC");
}
對於第二項測試,您想將其更改為:
new DateTime(0L, DateTimeZone.UTC);
注意,通常不應該使用靜態SimpleDateFormat
變量,因為它不是線程安全的。 (而Joda Time DateTimeFormatter
實現是線程安全的。)
您還可以使用 JUnit Pioneer: https ://junit-pioneer.org/docs/default-locale-timezone/
或者您可以比較日期並放入
@Ignore("Timezone issues")
@Test
在單元測試中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.