How to use stubs in JUnit and Java?

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


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";
    }
}

Tags:

Java

Junit

Stub