Quantum_Entanglement
Quantum_Entanglement

Reputation: 1633

Easy way to mock chained method calls in Easymock

Is there a simple way to mock this call:

objectA.getB().getC();

right now the way I do this is:

A mockA = EasyMock.createMock(A.class);
B mockB = EasyMock.createMock(B.class);
C mockC = EasyMock.createMock(C.class);

expect(mockA.getB()).andReturn(mockB);
expect(mockB.getC()).andReturn(mockC);

This is a bit of an overkill since all I care is to get mockC. Is there an easier way to do it?

Upvotes: 5

Views: 3839

Answers (2)

Lauri
Lauri

Reputation: 1899

I know the question is about EasyMock, but i can't just sit on my hands and not tell you about Mockito. The mocking you would like to do, is fairly easy in Mockito.

A mockA = Mockito.mock(A.class, RETURNS_DEEP_STUBS);
C mockC = Mockito.mock(C.class);
Mockito.when(mockA.getB().getC()).thenReturn(mockC);

Note that Mockito started off as enhancement to EasyMock, you may read more about it here: https://code.google.com/p/mockito/wiki/MockitoVSEasyMock

Upvotes: 1

Tammo Freese
Tammo Freese

Reputation: 10754

No, there isn't – if you want to replace A, B and C in your test with mocks, you need three mock objects.

Another approach is to use the real A and B classes, and only to replace C with a mock object. Then your unit test would test

  1. the class that contains objectA.getB().getC()
  2. A
  3. B

as a "unit" together. Whether this makes sense or not, depends on the concrete scenario.

Upvotes: 0

Related Questions