Unitils and the class that had no default constructor

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!

Advertisements

,

  1. #1 by Ben Dean on January 15, 2009 - 10:12 am

    I just found this when I was searching online with Google to find an answer to this question. Good thing this is an external blog (better yet, we should get a Google search app so google.com gives results on internal webpages too).

  2. #2 by danielmeyer on January 15, 2009 - 10:14 am

    That’s great! Glad to be of service. :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s