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...

No comments:

Post a Comment