A flaky test produces different results across runs even when code and inputs are unchanged. Timing-sensitive checks can pass for months, then fail when a boundary changes, disrupting continuous integration and wasting developers’ time. section 9.11
Comparing against a second clock reading
A backup-folder test calls createBackupFolder(), then calls LocalDateTime.now() again to construct the expected name. If the minute changes between calls, the assertion fails. Capture the relevant time once and use that value for both production behavior and the assertion. section 9.11
Reduce instability by avoiding assumptions that the world remains unchanged between related operations:
- Minimize separate filesystem queries when several attributes are needed; Files.readAttributes() obtains them together. section 9.11
- Prefer one operation that checks and uses filesystem state together when intervening changes could invalidate the result. 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);
}
Inspect the time-dependent assertion that makes the backup-folder test flaky. section 9.11

