Neha Arora Neha Arora - 1 month ago 17
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

Mockito.mock()
better than using
new
operator to create instances while writing Junit tests in Java?

Answer

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:

@Test
public void should_calculate_five_times() {
    // Create mock object
    Dependency dependencyMock = Mockito.mock(Dependency.class);
    // Simulate the behaviour of the mock object
    Mockito.when(dependencyMock.doWork()).thenReturn(2);

    // Create object under test
    Thing thingToTest = new Thing();
    // Inject mock object
    thingToTest.setDependency(dependencyMock);
    // Execute method to test
    thingToTest.calculate(5);

    // 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());
}
Comments