arquillian

Using the ShrinkWrap Maven Resolver for Arquillian Tests

This post assumes that you’re familiar with using Arquillian for testing Java applications. If you’re not familiar with Arquillian, then I suggest you check out the guides at http://www.arquillian.org/ where you’ll learn how to write Java tests that can run on the server and are much easier to write and maintain.

When writing an Arquillian test, you create a deployment as in the following code sample:

@Deployment
public static Archive<?> createTestArchive() {
return ShrinkWrap.create(JavaArchive.class, "test.jar")
.addClasses(RandomNumberBean.class);
}

It’s not uncommon to see a lot of calls to .addClasses() or .addPackages(). When working with third party libraries, this list of classes/packages added to the archive can grow and grow (and can be a bit of a trial and error process to get a complete list of dependencies). The ShrinkWrap Maven Resolver overcomes this issue by allowing you to specify Maven dependencies in the createTestArchive() method rather than having to add each class/package at a time.

To use the ShrinkWrap Maven Resolver, the first stage is to add the relevant dependency to you Maven project’s pom.xml file.

<dependency>
<groupId>org.jboss.shrinkwrap.resolver</groupId>
<artifactId>shrinkwrap-resolver-impl-maven</artifactId>
<scope>test</scope>
</dependency>

Having configured Maven, you’re ready to go and add dependencies to your Arquillian archive via code as shown in the sample below. In this sample, I’ve added the Apache Commons Math library to the Arquillian archive.

@Deployment
public static Archive<?> createTestArchive() {
MavenDependencyResolver resolver = DependencyResolvers.use(
MavenDependencyResolver.class).loadMetadataFromPom("pom.xml");

return ShrinkWrap
.create(WebArchive.class, "test.war")
.addClasses(RandomNumberBeanCommons.class)
.addAsLibraries(
resolver.artifact("org.apache.commons:commons-math")
.resolveAsFiles());
}

Looking at the code, you can see that the first stage is to create a MavenDependencyResolver from the project’s pom.xml file. Then all you need to do, is invoke the .addAsLibraries() method on the Arquillian deployment specifying which Maven dependency to resolve.

Hopefully, you can see that this technique allows you to create your Arquillian tests much faster and more reliably than without using the ShrinkWrap Maven Resolver.

3 thoughts on “Using the ShrinkWrap Maven Resolver for Arquillian Tests

  1. See also community.jboss.org/…/HowToIAddMavenArtifactsToMyShrinkWrapArchives – which addresses how to use the updated resolver with Arquillian 1.0.0.Final .

Comments are closed.