In order to verify the issue described yesterday, we obviously had to test it first. Only after writing a test that fails first and succeeds after changing the code, we can be sure that we found and fixed the actual problem. Another advantage of the test is that it allows you to debug the problem much faster. It saves you from performing a manual task over and over again.

What to test?

Since we assumed that the problem is related to reading resources from a compressed jar file, we should compare reading a file from a compressed and from an uncompressed jar. I’ve jarred up our public key twice (compressed and uncompressed) and put the files into the test resources directory. In our case src/etc/test.

Reading the resources

In order to make the jars available to the test, I’ve added the two jar files to the test resources. Now that the jars should be available as a resource, we still need to access the files within the jars. We can easily access the jar file by asking the ContextClassLoader for a resource. But this will only give us the jar file and not the actual files inside.
There are a few ways of accessing the contents of the jar. For starters we could unzip the content manually, the JDK offers a few classes to do so. But that might defeat the purpose of our test. Therefore we want to load the content with a class loader.
Since the invocation of getResource() returns a URL, the URLClassLoader seemed to be a good choice. It expects an Array of URLs which we now can happily provide. After creating a new instance of the URLClassLoader using the URL to our JAR, we can then access the resources within the jar through the classloader.


String testJar = "test.jar";
String fileName = "file.txt";
URL[] urls = new URL[]{Thread.currentThread().getContextClassLoader().getResource(testJar)};
URLClassLoader urlClassLoader = new URLClassLoader(urls);
InputStream inputStream = urlClassLoader.getResourceAsStream(fileName);

Reading Resources from a JAR for Unit-Tests