简体   繁体   English

在所有时区和带/不带 DST 的情况下进行带日期的单元测试

[英]Make unit tests with dates pass in all time zones and with/out DST

How do I make this unit test pass in all time zones independent of whether DST is active or not?无论 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() );
    }
}

By default, a new SimpleDateFormat will use the system default time zone. 默认情况下,新的SimpleDateFormat将使用系统默认时区。 If you want a specific time zone, you should call setTimeZone on it: 如果需要特定的时区,则应在其上调用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");
}

For your second test, you'd want to change it to: 对于第二项测试,您想将其更改为:

new DateTime(0L, DateTimeZone.UTC);

Note that you shouldn't usually use a static SimpleDateFormat variable, as it's not thread-safe. 注意,通常不应该使用静态SimpleDateFormat变量,因为它不是线程安全的。 (Whereas the Joda Time DateTimeFormatter implementation is thread-safe.) (而Joda Time DateTimeFormatter实现线程安全的。)

You can also use JUnit Pioneer: https://junit-pioneer.org/docs/default-locale-timezone/您还可以使用 JUnit Pioneer: https ://junit-pioneer.org/docs/default-locale-timezone/

Or you can compare the date and put 或者您可以比较日期并放入

@Ignore("Timezone issues")
@Test

In your unit-test 在单元测试中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM