Search code examples
javajunitstaticvoidpowermockito

How to mock overloaded public static method which returns void with PowerMockito


I got a problem mocking a public static method which returns void, when I want it to throw specific Exception (e.g. RuntimeException)

This is what I have so far:

@RunWith(PowerMockRunner.class)
@PrepareForTest(TheUtilsClass.class)
public class MyTest {
    @Test
    public void theTest() {
        PowerMockito.mockStatic(TheUtilsClass.class);
        PowerMockito.doThrow(new RuntimeException.class).when(TheUtilsClass.class, "methodToBeMocked", any(FirstParam.class), any(SecondParam.class));
    }
}

And this does not work because "methodToBeMocked" is overloaded several times. Instead I got the exception TooManyMethodsFoundException where I could not suppress other methods.


Solution

  • I have found solution myself, but could not find it online. Actually I just have created an Answer which throws the needed exception and that's it:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(TheUtilsClass.class)
    public class MyTest {
        @Test
        public void theTest() {
            PowerMockito.mockStatic(TheUtilsClass.class, new Answer<Void>() {
                @Override
                public Void answer(InvocationOnMock invocation) throws Throwable {
                    throw new RuntimeException();
                }
            });
        }
    }