How to use stubs in JUnit and Java?

Wooopsa picture Wooopsa · Aug 8, 2015 · Viewed 40.5k times · Source

I have worked with JUnit and Mocks but I'm wondering, what are the differences between Mocks and Stubs in JUnit and how to use Stubs in JUnit, Java? And as Mocks that have EasyMock, Mockito and so on, what does Stubs uses in Java?

Please give some example code for Stubs in Java.

Answer

Michael Baker picture Michael Baker · Aug 8, 2015

It doesn't matter the framework or technology in my opinion. Mocks and stubs could be defined as follows.

A stub is a controllable replacement for an existing dependency (or collaborator) in the system. By using a stub, you can test your code without dealing with the dependency directly.

A mock object is a fake object in the system that decides whether the unit test has passed or failed. It does so by verifying whether the object under test interacted as expected with the fake object.

Perhaps these images can clarify the interactions between a stub an mock.

Stub Stub

Mock Mock