Dan Haywood is a UK-based freelance consultant specializing in enterprise application development using domain driven design approaches and agile development. Technology skills include Java, JEE, .NET, Sybase, RDBMS, OOAD, UML, AOP, TDD, Subversion and TFS Dan is a committer and advocate of the Naked Objects framework, and the author of “Domain Driven Design using Naked Objects”, published by the Pragmatic Bookshelf. Dan is a DZone MVB and is not an employee of DZone and has posted 13 posts at DZone. You can read more from them at their website. View Full User Profile

Mockito-like Automocking and Optional Autowiring in JMock

07.18.2012
| 2324 views |
  • submit to reddit

I’m running my little TDD course again, and (as usual) it’s given rise to another small idea to make unit testing easier: provide Mockito-like automocking (using a @Mock annotation), and in addition perform autowiring of all mocks into the class under test.

Now, to be honest, the difficult bit, automocking, is already in the JMock codebase, but as of this writing it’s still not been released (come on guys!). So I’ve just taken that code and tweaked it to also support this idea of autowiring.

Here’s what it looks like in code:

public class JUnitRuleMockery2Test_autoWiring {

    @Rule
    public JUnitRuleMockery2 context = 
        JUnitRuleMockery2.createFor(Mode.INTERFACES_AND_CLASSES);

    @Mock
    private Collaborator collaborator;

    @ClassUnderTest
    private Collaborating collaborating;

    @Before
    public void setUp() throws Exception {
        collaborating = (Collaborating) context.getClassUnderTest();
    }
    
    @Test
    public void checkAutoWiring() {
        assertThat(collaborating, is(not(nullValue())));
        assertThat(collaborating.collaborator, is(not(nullValue())));
    }
}

Where to get this code? Well, since I’ve now blogged about a couple of utilities, I thought I’d upload them to this new github project. There’s the stuff from those posts and this one, as well as a couple of other goodies. Just pull it down and build with Maven.

As ever, feedback welcome!

 

Published at DZone with permission of Dan Haywood, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Witold Szczerba replied on Tue, 2012/07/24 - 4:27am

Hi,

I have proposed a pull request:
https://github.com/danhaywood/java-testsupport/pull/1

so one does not have to extra cast like in @Before method.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.