Over a million developers have joined DZone.

Mockito-like Automocking and Optional Autowiring in JMock

· Java Zone

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

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!

 

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

Topics:

Published at DZone with permission of Dan Haywood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}