mstrom
mstrom

Reputation: 1743

When do I need to implement interfaces for unit testing if I'm using Mockito?

I'm new to unit testing and Mockito. I code to interfaces for best practice but, since I use Mockito, when do I actually need to implement those interfaces for unit testing? Would I only need this if I'm looking for default values different than the ones Mockito mocks provide?

Thanks!

Upvotes: 0

Views: 117

Answers (1)

Kevin Welker
Kevin Welker

Reputation: 7937

You only "need" an implementation of the class under test ("system under test"). Any collaborators -- which may appear as either injected fields in your class under test, or as parameters to the methods you are calling on your class under test -- may be left as mocked interfaces.

However, the less real objects you use, the more complicated your test becomes as you have to re-write all of the expected behavior for those collaborators as "when(...)" statements. In essence, you practically end up writing the application code a whole second time as the "when(...)" statements.

I try to mock only "deep" objects that have a long chain of dependencies required in order to produce the test scenario I am trying to create. Things like entity classes, transfer objects, etc., should rarely be mocked, and hence they should usually be implemented. Other kinds of objects are a gray area.

Ultimately, you will always want to make sure your actual implementation classes are tested, otherwise there is no point to the test.

Upvotes: 2

Related Questions