-
Notifications
You must be signed in to change notification settings - Fork 3
Testing
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.
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>
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:
- Adding a
@GuiceConfig
annotation - Adding methods annotated with
@TestConfig
and returning Configuration, Properties or PropertyFile instances to add to the guice environment configuration - Adding
@TestModule
annotated methods returning guice Module implementations to be added to the guice environment configuration
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;
// ...
}
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());
}
// ...
}
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