Wednesday, October 17, 2018

Mocking void methods | Mockito


Mocking void methods with mockito

In this tutorial, we will see how to mock void methods and how to verify how many times the method is called

Below is the simple Utils class which contains printMessage method of type void

public class Utils {
    public void printMessage(String message){
        System.out.println(message);
    }
}

In order to mock this void method, we need to first mock the object of the respective class (Utils)

For example :-

@Mock
private Utils utils;

After this, call the method using this mocked variable and verify the number of times this method is executed

Test class for Utils :- 

@RunWith(MockitoJUnitRunner.class)
@PrepareForTest(Utils.class)
public class UtilsTest {
   
    @Mock
    private Utils utils;

    @Test
    public void ShouldReturn() {       
        utils.printMessage("hii");
        Mockito.verify(utils, times(0)).printMessage("hii");       
    } 
}

Without mocking the Object

Let's try to write the JUNIT for the same class without mocking the object.

@RunWith(MockitoJUnitRunner.class)
@PrepareForTest(Utils.class)
public class UtilsTest2 {

    private Utils utils;

    OutputStream os;

    @Before
    public void setup(){
        utils = new Utils();
        os = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(os);
        System.setOut(ps);
    }

    @Test
    public void ShouldReturn() {
        utils.printMessage("hii");
        assertEquals("hii",os.toString().trim());
    }

This will actually compare what it printed on the terminal with what we expect in the test

No comments:

Post a Comment