Thursday, September 22, 2011

And to mock a static void...

Next up, mocking a static void to make it do nothing and then verifiying it was called. Here's how I did it using PowerMock:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Thing.class)
public class MyTest {

   public void test() {

      // mock all static methods, rendering them useless/pointless
      PowerMockito.mockStatic(Thing.class)

      new Thing().save();

      // check save was called
      PowerMockito.verifyStatic();
      Thing.save();

   }

}

Wednesday, September 21, 2011

Mocking Roo Entities CRUD methods

When working with Roo it can be a pain to write true unit tests when your code interacts with CRUD/persistence methods on an Entity you've passed to it. The simple way around this is to use Mockito's 'spy' AKA partial mocking.

I tried this according to Mockito's documentation:
 Thing spy = spy(new Thing());
 when(spy.merge()).thenReturn(spy);
Unfortunately, as part of this code 'merge' is actually called, which will fail because Roo's logic attempts to merge the Mockito spy. The solution around this is to change how you setup the method stub:
 doReturn(spy).when(spy).merge();
For persist, i'd do
 doNothing().when(spy).persist();
I figured this out thanks to this page

Note that having to use a spy generally indicates poor design. Maybe that says something about Roo and its active record pattern...