Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test param value using EasyMock

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.

like image 346
fmpdmb Avatar asked Jan 18 '26 00:01

fmpdmb


2 Answers

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(), ???);
}
like image 141
fmpdmb Avatar answered Jan 20 '26 16:01

fmpdmb


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.

like image 32
Kartik Avatar answered Jan 20 '26 14:01

Kartik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!