chebs
chebs

Reputation: 33

Mockito doNothing doesn't work when a Method called with void method call inside

Main Class

public class BootSample {

    public int call(int m) {
        System.out.println("Entering into Call Method");
        int n = m*10;
        TestUtil testUtil = new TestUtil();
        testUtil.add(m, n);
        System.out.println("End of Call Method Value n : " + n);
        return n;
    }

}

Util Class

public class TestUtil {

    public void add(int a, int b) {
        System.out.println(" Entering into TestUtil Method ");
        int c = a +b;
        System.out.println(" End of TestUtil Method Value : " + c);
    }

}

Test Class

@RunWith(MockitoJUnitRunner.class)
public class BootSampleTest {

    @Mock
    TestUtil testUtil; 

    @Before
    public void setup() {

    }

    @Test
    public void utilSuccess() throws Exception {
        BootSample bootSample = new BootSample();
        doNothing().when(testUtil).add(any(Integer.class),any(Integer.class));
        int result = bootSample.call(10); 
        assertEquals(result,100);
    }

}

Output :

Entering into Call Method
 Entering into TestUtil Method 
 End of TestUtil Method Value : 110
End of Call Method Value n : 100

I'm trying to mock util void method call with doNothing but doesn't work.Can anyone please help me with solution? I'm stuck with similar functionality in our application.

Upvotes: 3

Views: 20491

Answers (3)

Utkarsh Kumar
Utkarsh Kumar

Reputation: 76

You can use Mockito.anyInt() instead of Integer.class, code example :

Mockito.doNothing().when(testUtil).add(Mockito.anyInt(),Mockito.anyInt());

Upvotes: 1

Kevin Hooke
Kevin Hooke

Reputation: 2621

If you're seeing the System.out.printlns from your TestUtil class then it isn't mocked. It looks like you're missing the @InjectMocks on BootSample to tell Mockito to inject your mocked TestUtil into it.

See the example in the docs here: http://static.javadoc.io/org.mockito/mockito-core/2.13.0/org/mockito/InjectMocks.html

Upvotes: 1

Eric
Eric

Reputation: 2076

The problem is that your call method is responsible for creating a TestUtil object, and that object can't be mocked. Try adding TestUtil as a constructor argument like so:

public class BootSample {

    private TestUtil testUtil;

    public BootSample(TestUtil testUtil) {
        this.testUtil = testUtil;
    }

    public int call(int m) {
        System.out.println("Entering into Call Method");
        int n = m*10;
        testUtil.add(m, n);
        System.out.println("End of Call Method Value n : " + n);
        return n;
    }
}

You then need to mock the TestUtil class and pass the mock to the BootSample class:

BootSample bootSample = new BootSample(testUtil);

Upvotes: 2

Related Questions