Neha Arora Neha Arora - 1 year ago 87
Java Question

How is Mockito.mock better that using new while writing Junit tests?

I am writing Junit tests for the first time and new to the Mockito framework.
How is using

better than using
operator to create instances while writing Junit tests in Java?

Answer Source

Mockito can be used to inject dependencies that might not be there in the current testing context, not to create "dummy" objects for testing. Those mock objects are not the real thing they're mocking, but "empty" versions of it, on which you can run all sorts of behaviour-simulating and result-verifying methods that are provided by Mockito.

For example following class:

class Thing {
    //Some external Dependency which provides the method 'int doWork()'
    private Dependency dependency;
    private int value;
    public void setDependency(Dependency dependency) {
        this.dependency = dependency;
    public int getValue() {
        return value;
    // Calculates something depending on the provided amount.
    public void calculate(int amount) {
        for(int i = 0; i < amount; i++) {
            value += dependency.doWork();

Then you could do something like this in your Test:

public void should_calculate_five_times() {
    // Create mock object
    Dependency dependencyMock = Mockito.mock(Dependency.class);
    // Simulate the behaviour of the mock object

    // Create object under test
    Thing thingToTest = new Thing();
    // Inject mock object
    // Execute method to test

    // Expected: dependency.doWork() should have been called 5 times
    Mockito.verify(dependencyMock, Mockito.times(5)).doWork();
    // Since dependencyMock returns 2, when doWork() is called, value should be 10
    Assert.assertEquals(10, thingToTest.getValue());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download