Sonntag, 31. Juli 2011

JMock HasProperty Expectations

Took me a while to define JMock expectations which verifies that a argument of mocked method has a defined set of properties with values.

Here my JMock based JUnit test:
import static org.fest.assertions.Assertions.*;
import static org.hamcrest.Matchers.*;
import org.hamcrest.Matcher;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TrackServiceTest
{
Mockery mockery = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
TrackService mockTrackService;
@Before
public void setup()
{
mockTrackService = mockery.mock(TrackService.class);
}
@After
public void tearDown()
{
mockery.assertIsSatisfied();
}
@Test
public void testPersitTrack()
{
final String jamesBlond = "James Blond";
final String allTheLostSouls = "All the Lost Souls";
// Setup Mock Object Track Service
mockery.checking(new MyExpectations() {{
oneOf(mockTrackService).persitTrack(
with(
any(Track.class),
andAllOf(
hasProperty("interpret", is(jamesBlond)),
hasProperty("album", is(allTheLostSouls)))
));
will(returnValue(null));
}});
// Execute SUT
Track track = mockTrackService.persitTrack(
TrackBuilder.track()
.withInterpret(jamesBlond)
.withAlbum(allTheLostSouls)
.build());
// Verify
assertThat(track).isNull();
}
class MyExpectations extends Expectations {
public <T> T with(Matcher<T> valueMatcher, Matcher<Object> matcher)
{
return (T) with(matcher);
}
public Matcher<Object> andAllOf(Matcher<Object> ... matchers)
{
return allOf(matchers);
}
}
}


Is there no better way to do this in JMock?