If you need a bunch of jar files you need to use in your tests, not as dependencies, but as artifacts you need to use in the tests, you may have wondered how to do that without resorting to storing the jars in source control or having an elaborate build set up where test archives would be built prior to the tests needing them.
This library brings simplicity to the picture. No need to invoke the compiler yourself, automatic cleanup taken care of.
@ExtendWith(CompiledJarExtension.class)
class MyTestClass {
@JarSources(root = "/sources-on-classpath/", sources = {"a/MyClass.java", "b/MyOtherClass.java"})
private CompiledJar jarFile;
@Test
void test() {
//directory containing the compiled classes
jarFile.classes();
//the actual jar file containing the compiled sources
jarFile.jarFile();
CompiledJar.Environment env = jarFile.analyze();
//analyze the compiled classes as if in annotation processor
TypeElement myClass = env.elements().getTypeElement("a.MyClass");
}
}
It is possible to declare dependencies between the jars or declare a dependency on a 3rd party archive using some resolver.
Declaring dependencies between 2 compiled jars is as simple as assigning names to the jars and then using those names
in the @Dependencies
annotation like this:
@ExtendWith(CompiledJarExtension.class)
class MyTestClass {
@JarSources(name = "core", root = "/sources-on-classpath/", sources = {"a/MyClass.java", "b/MyOtherClass.java"})
private CompiledJar coreJar;
@JarSources(root = "/sources-on-classpath/", sources = {"a/MyClass.java", "b/MyOtherClass.java"})
@Dependencies({"core"})
private CompiledJar implJar;
// ...
}
Using a custom resolver is also possible:
@ExtendWith(CompiledJarExtension.class)
class MyTestClass {
@JarSources(root = "/sources-on-classpath/", sources = {"a/MyClass.java", "b/MyOtherClass.java"})
@Dependencies(resolver = MavenCacheDependencyResolver.class, value = {"com.acme:acme-api:42.0"})
private CompiledJar jar;
// ...
}
public class MyTestClass {
@Rule
public Jar jar = new Jar();
@Test
public void test() {
CompiledJar jarFile = jar.from()
.classpathSources("/sources-on-classpath/", "a/MyClass.java", "b/MyOtherClass.java")
.build();
// now it works the same as above
}
}
public class MyTestClass {
@Rule
public Jar jar = new Jar();
@Test
public void test1() {
CompiledJar jarFile = jar.from(new MavenCacheDependencyResolver())
.classpathSources("/sources-on-classpath/", "a/MyClass.java", "b/MyOtherClass.java")
.dependencies("com.acme:my-dep:42.0", "com.google:guava:132")
.build();
// ...
}
@Test
public void test1() {
CompiledJar baseJar = jar.from()
.classpathSources("/sources-on-classpath/", "a/MyClass.java", "b/MyOtherClass.java")
.build();
CompiledJar jarFile = jar.from(new MavenCacheDependencyResolver())
.classpathSources("/sources-on-classpath/", "dep/DepClass.java")
.dependencies(baseJar.jarFile())
.build();
// ...
}
}