### Question:
TrustOnFirstUseManager extends AbstractTrustManager { @Override public void checkServerTrusted(X509Certificate[] serverCertificates, String authType) throws CertificateException { checkTrusted(serverCertificates); } TrustOnFirstUseManager(Path knownHosts); @Override void checkClientTrusted(X509Certificate[] clientCertificates, String authType); @Override void checkServerTrusted(X509Certificate[] serverCertificates, String authType); @Override X509Certificate[] getAcceptedIssuers();  }### Answer:
@Test public void testFailedToGenerateWhiteListFile() throws IOException, CertificateEncodingException { Path anotherFile = Paths.get(tmpDir.getRoot().getPath(),"parent", "anotherFile"); tmpDir.getRoot().setWritable(false); trustManager = new TrustOnFirstUseManager(anotherFile); when(certificate.getEncoded()).thenReturn("certificate".getBytes(UTF_8)); X500Principal cn = new X500Principal("CN=localhost"); when(certificate.getSubjectX500Principal()).thenReturn(cn); try { trustManager.checkServerTrusted(new X509Certificate[]{certificate}, "str"); failBecauseExceptionWasNotThrown(IOException.class); } catch (Exception ex) { assertThat(ex) .isInstanceOf(CertificateException.class) .hasMessageContaining("Failed to save address and certificate fingerprint to whitelist"); } verify(certificate).getEncoded(); verify(certificate).getSubjectX500Principal(); tmpDir.getRoot().setWritable(true); }
@Test public void testGenerateWhiteListFileNoParentDirectory() throws IOException, CertificateException { Path anotherFile = Paths.get("anotherFileInRootDir"); trustManager = new TrustOnFirstUseManager(anotherFile); when(certificate.getEncoded()).thenReturn("certificate".getBytes(UTF_8)); X500Principal cn = new X500Principal("CN=localhost"); when(certificate.getSubjectX500Principal()).thenReturn(cn); assertThat(Files.exists(anotherFile)).isFalse(); trustManager.checkServerTrusted(new X509Certificate[]{certificate}, "str"); assertThat(Files.exists(anotherFile)).isTrue(); verify(certificate).getEncoded(); verify(certificate).getSubjectX500Principal(); Files.deleteIfExists(anotherFile); assertThat(Files.exists(anotherFile)).isFalse(); }
@Test public void testCertificateNotValidForRecognisedAddress() throws CertificateException, IOException { testAddThumbPrintToKnownHostsList(); when(certificate.getEncoded()).thenReturn("ADifferentCertificate".getBytes(UTF_8)); X500Principal cn = new X500Principal("CN=localhost"); when(certificate.getSubjectX500Principal()).thenReturn(cn); try { trustManager.checkServerTrusted(new X509Certificate[]{certificate}, "str"); failBecauseExceptionWasNotThrown(IOException.class); } catch (Exception ex) { assertThat(ex) .isInstanceOf(CertificateException.class) .hasMessageContaining("This address has been associated with a different certificate"); } verify(certificate, times(3)).getEncoded(); verify(certificate, times(3)).getSubjectX500Principal(); }