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.

+2


a source to share


4 answers


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

      

+8


a source


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'm not sure about the syntax on my head, but this should work.

+1


a source


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

      

This ensures that setBar was called with the Bar class as a parameter.

0


a source


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);
}

      

0


a source







All Articles