简体   繁体   English

Java,TDD 不等于时为真?

[英]Java, TDD True when not equals?

for some reason while testing this method during a lesson in class we found an issue we couldn't understand.由于某种原因,在 class 的课程中测试此方法时,我们发现了一个我们无法理解的问题。 When writing System.out.println();当写System.out.println(); for some reason it passes?.由于某种原因它通过了? Can someone explain why this is happening?有人可以解释为什么会这样吗?

public class Zones {

public ZoneId getZoneId(String input) {

    if (input.equalsIgnoreCase("Stockholm")) {
        return ZoneId.of("Europe/Stockholm");
    }
    else if (input.equalsIgnoreCase("Shanghai")) {
        return ZoneId.of("Asia/Shanghai");
    } else if (input.equalsIgnoreCase("Toronto")) {
        return ZoneId.of("America/Toronto");
    }
    else if (input.equalsIgnoreCase("Hamburg")) {
        return ZoneId.of("Europe/Berlin");
    }
    else return null;
}

public LocalDateTime getZoneTime(ZoneId zoneId) {
    LocalDateTime lt = LocalDateTime.now(zoneId);
    return lt;
}

} }

private Zones z = new Zones();

@Test
public void getZoneTimeTest () {
    System.out.println(z.getZoneTime(zIDToronto).getNano() );
    System.out.println(LocalDateTime.now(zIDToronto).getNano() );
    assertTrue(z.getZoneTime(zIDToronto).getNano() == LocalDateTime.now(zIDToronto).getNano());
}

The test involves race condition and passes (sometimes) because of the timing and adding statements changes the timing and therefore test outcome.测试涉及竞争条件并通过(有时)因为时间和添加语句会更改时间并因此更改测试结果。

The condition that is checked in the assertion basically is the equality of the nanoseconds parts of two date-times taken one after another in succession.断言中检查的条件基本上是连续取的两个日期时间的纳秒部分是否相等。

Given that by default System.currentTimeMillis() is used internally by LocalDateTime.now and it has at most millisecond precision the check will succeed if the second sequence of invocations to get the number of nanoseconds is quick enough (that is the actual sequence of calls leading to invocation of System.currentTimeMillis finished within the same millisecond as the first).鉴于默认情况下System.currentTimeMillis()LocalDateTime.now在内部使用,并且它最多具有毫秒精度,如果获取纳秒数的第二个调用序列足够快(即实际调用序列),则检查将成功导致System.currentTimeMillis的调用在与第一个相同的毫秒内完成)。

When you invoke the functions used to obtain the value of nanosecond before the actual assertion the corresponding classes are loaded, the code of corresponding methods get into the CPU caches etc. This makes the second pair of calls to get the number of nanoseconds run much quicker.当您在实际断言加载相应类之前调用用于获取纳秒值的函数时,相应方法的代码会进入 CPU 缓存等。这使得第二对获取纳秒数的调用运行得更快.

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

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