javajunitstub

How to use stubs in JUnit and Java?


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.


Solution

  • 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 and a mock.

    Stub Stub

    Mock Mock