emmby
emmby

Reputation: 100454

How to create a "deep" mock with EasyMock

I have a testcase that indirectly uses a class Foo. I don't care what Foo is for the purposes of the test case. I should just be able to mock it.

Foo mock = EasyMock.createMock(Foo.class);

However, the testcase uses a library that calls a few methods on Foo. Some of those methods return objects, and this library then calls a few methods on those returned objects. For the purposes of this test it doesn't matter what these objects are, just that they aren't null and don't cause NullPointerExceptions.

I've been going through and adding a whole bunch of expect calls like the following for every object and method that this library calls:

Bar bar = EasyMock.createMock(Bar.class);
Baz baz = EasyMock.createMock(Baz.class);
EasyMock.expect(mock.getBar()).andReturn(bar).anyTimes();
EasyMock.expect(bar.getBaz()).andReturn(baz).anyTimes();

Basically, just over and over creating expectations for any of the methods that this library ends up calling.

Again, the objects themselves don't matter for the purposes of my test. The library just needs them to be non-null for the most part.

Is there a way to automate this? What I'd like is some sort of "deep mock" capability, where I could tell EasyMock to automatically return mock objects for any objects obtained via a mock object.

Upvotes: 3

Views: 631

Answers (1)

emmby
emmby

Reputation: 100454

Turns out that mockito has this functionality built in:

Foo mock = Mockito.mock(Foo.class, Mockito.RETURNS_DEEP_STUBS);

Upvotes: 3

Related Questions