Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java unit tests set Manifest property

Is there a way at test time, to inject a property into the Java Manifest (or inject an entire manifest)?

We're reading a value from the manifest (version number) which at test time resolves to null.

So far we've tried putting a hard coded MANIFEST.MF file in our test root, but it didn't work.

This is the code we use to read the manifest:

private Attributes getManifest() {
    URLClassLoader cl = (URLClassLoader) getClass().getClassLoader();
    Manifest manifest;
    try {
        URL url = cl.findResource("META-INF/MANIFEST.MF");
        manifest = new Manifest(url.openStream());
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
    return manifest.getMainAttributes();
}

As a last resort we'll wrap the functionality that reads the manifest and mock it, but these are integration tests, and are supposed to be black box (ie, we're avoiding mocking).

Extra information: Java 7, Running Junit tests in IntelliJ or from Gradle.

like image 274
Andrew M Avatar asked Jun 25 '14 14:06

Andrew M


1 Answers

You might want to try the jcabi-manifests library: http://manifests.jcabi.com/. It's an abstraction of the the Java manifests facility and allows you to append new data or even combine multiple manifests at runtime.

Typical usage would be to access the Manifests.DEFAULT singleton, which holds your application's MANIFEST.MF entries at runtime. It's possible to append to this object:

Manifests.DEFAULT.put("Test-Property", "Hello");

Manifests Javadoc: http://manifests.jcabi.com/apidocs-1.1/com/jcabi/manifests/Manifests.html

Now, whenever you access Manifests.DEFAULT again, it will have the entry "Test-Property". Note that Manifest.DEFAULT implements the Map interface:

System.out.println(Manifests.DEFAULT.get("Test-Property")) // Prints "Hello"
like image 95
Carlos Miranda Avatar answered Nov 07 '22 10:11

Carlos Miranda