views:

205

answers:

4

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.

A: 
f.setBar(EasyMock.isA(Bar.class))

This will ensure setBar was called with a Bar class as a parameter.

Samuel Carrijo
+1  A: 

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(), ???);
}
fmpdmb
A: 

I'd construct an Object which is equal to the one I expect to get back. In this case, I'd create a new Bar and set it's ID to 123, relying on the correct implementation of equals() and hashCode() of Bar and the default behavior of EasyMocks argument matcher (using equal comparison for 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);
}
mhaller
I would argue this is more a test of the implementation of Bar than the method you're intending to test.
fmpdmb
A: 

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.

Kartik