Unitils is so helpful for unit testing. The top portion of my unit tests tend to look something like this:
@RunWith(UnitilsJUnit4TestClassRunner.class)
public class BongoTest {
@Mock
@InjectIntoByType
private Foo foo;
@Mock
@InjectIntoByType
private Baz baz;
@TestedObject
private Bongo bongo;
//...
And then Unitils automatically instantiates a Bongo and injects the Foo and Baz mocks into the Bongo’s fields of those respective types. My @Test methods can just start testing Bongo’s methods without worrying about the mock creation and injection and tested object instantiation. I’m free to get right to testing Bongo out. Nice!
This time, though, there was a twist: my TestedObject (call it a Congo) didn’t have a default constructor — instead, it needed a Foo and a Baz passed to its constructor. How to do that with the annotations?
On the Unitils cookbook page, it says:
The field annotated with @TestedObject is automatically instantiated with an instance of the declared type, if necessary (i.e. if not instantiated during test setup) and possible (i.e. if the declared type is a non-abstract class and offers an empty constructor).
So it looks like I have to take on a little responsibility myself this time. It ends up looking like this (notice the new @Before method):
@RunWith(UnitilsJUnit4TestClassRunner.class)
public class CongoTest {
@Mock
private Foo foo;
@Mock
private Baz baz;
@TestedObject
private Congo congo;
@Before
public void setUp() {
congo = new Congo(foo, baz);
}
//...
(Everything else is as, er… Before.)
That’s not too bad!