Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use stubs in JUnit and Java?

Tags:

java

junit

stub

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.

like image 982
Wooopsa Avatar asked Aug 08 '15 07:08

Wooopsa


People also ask

How do I use stubs in JUnit?

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.

How do you stub in unit testing?

To use stubs, you have to write your component so that it uses only interfaces, not classes, to refer to other parts of the application. This is a good design practice because it makes changes in one part less likely to require changes in another. For testing, it allows you to substitute a stub for a real component.

What is stub code in Java?

A method stub or simply stub in software development is a piece of code used to stand in for some other programming functionality. A stub may simulate the behavior of existing code (such as a procedure on a remote machine; such methods are often called mocks) or be a temporary substitute for yet-to-be-developed code.


2 Answers

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

like image 119
Michael Baker Avatar answered Oct 23 '22 03:10

Michael Baker


To use stubs in junit you don't need any frameworks.

If you want to stub some interface just implement it:

interface Service {
    String doSomething();
}

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

Then create new stub object and inject it to tested object.

If you want to stub a concrete class, create subclass and override stubbed 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";
    }
}
like image 21
Sergii Lagutin Avatar answered Oct 23 '22 02:10

Sergii Lagutin