### Question:
KeystoreLocker { public void lockKeystore(Path keystoreFile) { Path lockfilePath = Path.of(keystoreFile.toString() + ".lock"); try { if (lockfilePath.toFile().exists()) { attemptReplaceStaleLockFile(lockfilePath); } else { createNewLock(lockfilePath); } lockfilePath.toFile().deleteOnExit(); } catch (FileAlreadyExistsException e) { throw keystoreInUseException(keystoreFile); } catch (IOException e) { throw new UncheckedIOException("Unexpected error when trying to lock a keystore file.", e); } }  void lockKeystore(Path keystoreFile); void attemptReplaceStaleLockFile(final Path lockfilePath);  }### Answer:
@Test void shouldLockKeystoreFileAndFailWhenTryingCreateLockForLockedFile( final @TempDir Path keystoreFile) throws Exception { Assertions.assertThatCode(() -> keystoreLocker.lockKeystore(keystoreFile)) .doesNotThrowAnyException(); Assertions.assertThatThrownBy(() -> keystoreLocker.lockKeystore(keystoreFile)) .isExactlyInstanceOf(InvalidConfigurationException.class); }
@Test void doNotDeleteIfLockfileIsEmpty(final @TempDir Path keystoreFile) throws Exception { createLockfileWithContent(keystoreFile, new byte[0]); Assertions.assertThatThrownBy(() -> keystoreLocker.lockKeystore(keystoreFile)) .isExactlyInstanceOf(InvalidConfigurationException.class); }
@Test void doNotDeleteIfLockfileContainsSomethingThatIsNotLong(final @TempDir Path keystoreFile) throws Exception { createLockfileWithContent(keystoreFile, new byte[Long.BYTES + 1]); Assertions.assertThatThrownBy(() -> keystoreLocker.lockKeystore(keystoreFile)) .isExactlyInstanceOf(InvalidConfigurationException.class); }
@Test void throwIOExceptionWhenTryingToLockNonExistentKeystoreInNonExistingDirectory( final @TempDir Path keystoreFile) { Path nonExistingKeystoreFile = Path.of(keystoreFile.toString() + "/yo/keystore.json"); Assertions.assertThatThrownBy(() -> keystoreLocker.lockKeystore(nonExistingKeystoreFile)) .isExactlyInstanceOf(UncheckedIOException.class); }