I'm attempting to write some unit tests using EasyMock and TestNG and have run into a question. Given the following:
void execute(Foo f) {
Bar b = new Bar()
b.setId(123);
f.setBar(b);
}
I'm trying to test that the Id of the Bar gets set accordingly in the following fashion:
@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 can't just call f.getBar() and inspect it's Id because f is a mock object. Any thoughts? Is this where I'd want to look at the EasyMock v2.5 additions andDelegateTo() and andStubDelegateTo()?
Oh, and just for the record... EasyMock's documentation blows.
Ah ha! 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(), ???);
}
Have you tried this?`
final Bar bar = new Bar();
bar.setId(123);
EasyMock.expect(f.getBar()).andAnswer(new IAnswer<Bar>() {
public Bar answer() {
return bar;
}
});
I am not sure of the syntax on top of my head but this should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With