Introduction
Although using container in unit test is categorized as an anti-pattern (http://www.picocontainer.orgcom/tests-use-container-antipattern.html), it is interesting to use pico to bootstrap your test.
The anti-pattern seems to blame when you use a real container with real dependencies for a unit tests. But I think it's acceptable when
...
To lighten the container management in the test, a junit custom runner has been created which initialize the container and inject dependencies in the test class.
Usage of PicoRunner
PicoRunner is a simple junit custom runner which allows nice integration of picoContainer in Junit.
To get the full code of PicoRunner with examples, you can check IzPack sources.
Principle
Basically, in your test class, you define a container (implementing BindeableContainer) to use with the @Container annotation.
...
Code Block |
---|
@Override
protected Object createTest() throws Exception {
Class<? extends BindeableContainer> containerClass =
getTestClass().getJavaClass().getAnnotation(Container.class).value();
BindeableContainer installerContainer = getContainerInstance(containerClass);
installerContainer.initBindings();
installerContainer.addComponent(klass);
Object component = installerContainer.getComponent(klass);
return component;
}
|
Examples
Simple test
The first step is to create your container for test purpose.
Code Block |
---|
public class StupidTestContainer extends AbstractContainer { /** * Init component bindings */ public void fillContainer(MutablePicoContainer pico) { pico.addComponent( System.getProperties() ) .addComponent(Mockito.mock(List.class) ) } } |
Here we have 2 components, a Properties and a mock list.
...
Code Block |
---|
@RunWith(PicoRunner.class) @Container(StupidTestContainer.class) public class StupidTest { private List mockedList; public StupidTest(Properties property, List list) { this.mockedList = list; } @Test public void testList() throws Exception { //using mock list mockedList.add("one"); mockedList.clear(); //verification verify(mockedList).add("one"); verify(mockedList).clear(); } } |
Panel display tests
The following examples are taken from the izpack-test-panel module which contains small and fast GUI tests
...