Search code examples
javaunit-testingjunitmockitopowermockito

Mockito: Unable to mock a static & non-static method


I am unable to mock anything(static or non static methods) from mockito,

These are my classes,

Calculations.java

public class Calculations {

    public void printZero() {
        System.out.println("zero");
    }

    public static void printOne() { 
         System.out.println("one");
    }
}

This is my PostData.java

public class PostData {

    public static Calculations calc = new Calculations();
    public static void postTheData() {

        calc.printZero();
        Calculations.printOne();
    }
}

The unit test class, TestClass.java

public class TestClass {

    @Test
    public void addTest() {

        Calculations lmock = mock(Calculations.class);

        // can't have Calculations.calc.printZero() in when() :cause: argument passes to when() must be a mock object.
        doNothing().when(lmock).printZero();

        // cause: method when(void) is undefined for the type TestClass
        // when(lmock.printZero()).doNothing();

        // cause: argument passed to when() must be a mock object.
        // doNothing().when(Calculations.printOne());

        PostData.postTheData();
    }
}

Its compiled and its printing "zero" as well as "one" in my output, which ideally should have been ignored.

I am using cloud-mockito-all-1.10.19.jar for mockito. And junit's latest jar file.

I know I am missing something here, but can't figure out what! It would be a great help if you can answer me.


Solution

  • The problem is that PostData doesn't use the mocked Calculations object.

    In order to do it, you can add a setter for calc field (and perhaps change it to be non static) and set PostData's calc field to the mocked one.