JarExtractor { public Path extractToTemp(String filenameWithoutSuffix) { String filename = filenameWithoutSuffix + ".jar"; URL url = getClass().getResource("/" + filename); try { Path copy = Files.createTempFile(filenameWithoutSuffix, ".jar"); copy.toFile().deleteOnExit(); try (InputStream in = url.openStream()) { Files.copy(in, copy, StandardCopyOption.REPLACE_EXISTING); } return copy; } catch (Exception e) { throw new IllegalStateException("Fail to extract " + filename, e); } }  Path extractToTemp(String filenameWithoutSuffix);  }
@Test public void test_extract() throws Exception { Path jarFile = new JarExtractor().extractToTemp("fake"); assertThat(jarFile).exists(); assertThat(new String(Files.readAllBytes(jarFile), StandardCharsets.UTF_8)).isEqualTo("Fake jar for unit tests"); assertThat(jarFile.toUri().toURL().toString()).doesNotContain("jar:file"); }
@Test public void should_fail_to_extract() throws Exception { try { new JarExtractor().extractToTemp("unknown"); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("Fail to extract unknown.jar"); } }