Java unit tests set Manifest property
Asked Answered
B

1

8

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.

Balcke answered 25/6, 2014 at 14:7 Comment(2)
So, when you run a test, where is MANIFEST.MF is located, exactly?Thickness
Why do you want to modify java manifest when you are running tests (probably JUnit?) when test is a standalone java application and not an application running in a container?Maynor
C
2

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"
Cowbind answered 10/9, 2015 at 4:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.