Below is a class StudentUtils which contains only two Method – doNothingWhenCalled and dummymethod. We are going to unit test doNothingWhenCalled method.

The conclusion would be to use @Spy when we mock methods of same class tested to doNothing and use @Mock to mock method to doNothing call to other classes.

StudentUtils.java

package com.mugil.org;

import java.util.ArrayList;
import java.util.List;

public class StudentUtils {
    private List arrStudents = new ArrayList();
    private String Name = "Mugil";

    public StudentUtils(){
        arrStudents.add(new Student("101", "Mugil"));
    }

    public Student doNothingWhenCalled()
    {
        dummymethod(new Student("102" ,"abc"));
        return new Student("103", "StudentName");
    }

    public String dummymethod(Student objStudent)
    {
        System.out.println("Dummy Method Called");
        return "Dummy Method";
    }

@InjectMocks
StudentUtilsTest.java

@ExtendWith({MockitoExtension.class})
class StudentUtilsTest {
    @InjectMocks
    StudentUtils systemUnderTest;

    @Test
    void doNothingCalled() {
        Assertions.assertThat(systemUnderTest.doNothingWhenCalled()).isInstanceOf(Student.class);
    }
}

Output

Dummy Method Called

@Mocks
StudentUtilsTest.java

@ExtendWith({MockitoExtension.class})
class StudentUtilsTest {
    @InjectMocks
    StudentUtils systemUnderTest;

    @Test
    void doNothingCalled() {
        systemUnderTest = Mockito.mock(StudentUtils.class);
        Mockito.when(systemUnderTest.dummymethod(any())).thenReturn("Dummy Method");

        Assertions.assertThat(systemUnderTest.doNothingWhenCalled()).isInstanceOf(Student.class);
    }
}

You can see below we are trying to call method to be tested under empty mock instance which doesnot have default method definition. There is no point in mocking method definition since systemUnderTest.doNothingWhenCalled() would try to invoke test method which has no idea about.
Output

java.lang.AssertionError: 
Expecting actual not to be null

@Spy
StudentUtilsTest.java

@ExtendWith({MockitoExtension.class})
class StudentUtilsTest {
    @InjectMocks
    StudentUtils systemUnderTest;

    @Test
    void doNothingCalled() {
        systemUnderTest = Mockito.spy(StudentUtils.class);
        Assertions.assertThat(systemUnderTest.doNothingWhenCalled()).isInstanceOf(Student.class);
    }
}

Output

Dummy Method Called

Below is the Debug of Object created using @Mock, @InjectMock and @Spy.As you can see the one with Mock contains only MockInterceptor which does not have definition of methods on its own where as @InjectMock created instance of TestClass. @Spy contains both MockInterceptor and Instance enabling partial mock.

While Using InjectMock you can see the MockitoInterceptor in scope

While Using InjectMock you can see the class variables getting initialized

While Using Spy you can see both class variables getting initialized and MockitoInterceptor in scope

Comments are closed.