Current time is an external value that can change while a computation runs, including when a machine is suspended or execution crosses midnight. section 9.11
A flaky backup-folder test
A backup-folder method and its test each call LocalDateTime.now(). Usually both calls produce the same hour and minute, but a minute boundary can make the expected name differ from the actual folder name, causing a sporadic test failure. section 9.11
Treat clock-derived values as unstable inputs:
- Do not assume that a value read from the external world will remain unchanged during later computation. section 9.11
- Recognize that seemingly rare timing differences can become observable at boundaries such as a new minute or day. section 9.11
@Test
public void testBackupFolder() throws IOException {
Path tempDir = Files.createTempDirectory("test");
Path backupFolder = createBackupFolder(tempDir); #1
var nameFormat = DateTimeFormatter.ofPattern(
"'Backup'-yyyy-MM-dd-HH-mm");
String expectedName = nameFormat.format(LocalDateTime.now());
assertEquals(backupFolder.getFileName().toString(),
expectedName);
}
Shows the test pattern that reads the current time separately from backup-folder creation. section 9.11
