繁体   English   中英

在所有时区和带/不带 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.

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