Skip to content

Testing

petergeneric edited this page Dec 1, 2014 · 2 revisions

Where possible it's best to have unit tests that do not require guice, however when it is necessary to involve guice (e.g. for integration tests) the framework has a JUnit runner implementation to build and tear down guice environments for each test (and to parameterise test methods). This runner works in a similar fashion to Jukito.

pom.xml dependencies

Insert the following into your pom.xml:

<dependency>
	<groupId>com.peterphi.std.guice</groupId>
	<artifactId>stdlib-guice-testing</artifactId>
	<version>${stdlib.version}</version>
	<scope>test</scope>
</dependency>

Configuration

Tests should be annotated with @RunWith(GuiceUnit.class). Additional configuration of the guice environment (e.g. setting a restricted package for class scanning) can be made using the following routes:

  1. Adding a @GuiceConfig annotation
  2. Adding methods annotated with @TestConfig and returning Configuration, Properties or PropertyFile instances to add to the guice environment configuration
  3. Adding @TestModule annotated methods returning guice Module implementations to be added to the guice environment configuration

Mocks

It is possible to auto-bind mocks by adding the @Automock annotation to members of your JUnit test class. Mocks will not be automatically bound against any other bindings in your project, so your JUnit class will show clearly what bindings a given test depends on.

@RunWith(GuiceUnit.class)
public class MyTest {
	@Automock
	@Inject
	SomeRestService remote;

	// ...
}

Example Test Code

The following example is taken from the guice-hibernate module.

@RunWith(GuiceUnit.class)
@GuiceConfig(config = "hibernate-tests-in-memory-hsqldb.properties",
             classPackages = QEntity.class)
public class HqlChildCountTest
{
	@Inject
	QDao dao;

	/**
	 * Simple test that using HQL works
	 *
	 * @throws Exception
	 */
	@Test
	public void testEmptyDb() throws Exception
	{
		List<Long> ids = dao.getIdsByQuery("select q.id from Q q");

		assertEquals(0, ids.size());
	}

	// ...
}

Parameterised tests

When writing a @Test method it is possible to specify the @TestEach annotation on one or more parameters and supply a list of values. In this case the test method will be replicated to call every combination of @TestEach values. For example:

@Test
public void testTestEach(@TestEach("a","b") String a, @TestEach("x","y") String x) {
	System.out.println(a + x);
}

The above test will output the following lines:

ax
bx
ay
by