Java - How to use stubs in JUnit

I worked with JUnit and Mocks, but I wonder what are the differences between Mocks and Stubs in JUnit and how to use Stubs in JUnit, Java? And like Mocks that have EasyMock, Mockito, etc. What uses Stub in Java?

Please give a sample code for Stub in Java.

Thanks!

+6
source share
2 answers

To use stubs in junit, you do not need any frameworks.

If you want to drown out some kind of interface, just do it:

interface Service { String doSomething(); } class ServiceStub implements Service { public String doSomething(){ return "my stubbed return"; } } 

Then create a new stub object and add it to the test object.

If you want to remove a specific class, create a subclass and override the encoded methods:

 class Service { public String doSomething(){ // interact with external service // make some heavy computation return "real result"; } } class ServiceStub extends Service { @Override public String doSomething(){ return "stubbed result"; } } 
+11
source

In my opinion, the framework or technology does not matter. Mocks and stubs can be defined as follows.

A piece is a controlled replacement for an existing dependency (or co-author) in a system. Using a stub, you can test your code without accessing the dependency directly.

An object layout is a fake object in the system that decides whether a unit test passed or failed. He does this by checking if the object interacted under the test, as expected, with the fake object.

Perhaps these images may clarify the interaction between the stub and layout.

Stub Stub

Mock Mock

+12
source

All Articles