Search code examples
javaunit-testingjunitmockingjunit5

How to unit test static methods with custom object as return type using JUnit 5


public class Demo{
    public static CustomObject processMethod(String str1, String str2){
        //do something
        Demo1.processMethod1(str1,str2);
        Demo2.processMethod2(str1,str2);
        return custom Object;
    }
}

public class Demo1{
    public static void processMethod1(String str1, String str2){}
}

public class Demo2{
    public static void processMethod2(String str1, String str2){}
}

I am new to unit testing. While creating a test for class Demo processMethod, how to skip the execution of processMethod1 and processMethod2?


Solution

  • Beware that the void method on mocks does nothing by default!

    you can use any of the doThrow(),doAnswer(),doNothing(),doReturn() family of methods from Mockito framework to mock void methods.

    For example,

    Mockito.doThrow(new Exception()).when(instance).methodName();
    

    or if you want to combine it with follow-up behavior,

    Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();
    

    or do nothing:

    Mockito.doNothing().when(spy).methodToMock();
    

    or you can call real method

    Mockito.doCallRealMethod().when(<objectInstance>).<method>();
    <objectInstance>.<method>();
    

    Or, you could call the real method for all methods of that class, doing this:

    <Object> <objectInstance> = mock(<Object>.class, Mockito.CALLS_REAL_METHODS);