Test parameter value with EasyMock
I am trying to write some unit tests using EasyMock and TestNG and came across a question. Considering the following:
void execute(Foo f) {
Bar b = new Bar()
b.setId(123);
f.setBar(b);
}
I am trying to verify that the panel id is set like this:
@Test
void test_execute() {
Foo f = EasyMock.createMock(Foo.class);
execute(f);
Bar b = ?; // not sure what to do here
f.setBar(b);
f.expectLastCall();
}
In my test, I cannot just call f.getBar()
and check its Id because it f
is a mock object. Any suggestions? This is where I want to look at the EasyMock v2.5 andDelegateTo()
and add-ons andStubDelegateTo()
?
Oh, and just for the record ... EasyMock documentation will hit.
a source to share
Aha! Capture is the key.
@Test
void test_execute() {
Foo f = EasyMock.createMock(Foo.class);
Capture<Bar> capture = new Capture<Bar>();
f.setBar(EasyMock.and(EasyMock.isA(Bar.class), EasyMock.capture(capture)));
execute(f);
Bar b = capture.getValue(); // same instance as that set inside execute()
Assert.assertEquals(b.getId(), ???);
}
a source to share
I would build the object equal
that I expect to receive. In this case, I would create new Bar
and set its ID to 123, relying on the correct implementation of equals()
both hashCode()
of Bar
and the default behavior for EasyMocks parameter matching (using equal comparison for the parameters).
@Test
public void test_execute() {
Foo f = EasyMock.createMock(Foo.class);
Bar expected = new Bar();
expected.setId(123);
f.setBar(expected);
EasyMock.expectLastCall();
EasyMock.replay(f);
execute(f);
EasyMock.verify(f);
}
a source to share