I am new to Mockito and PowerMockito. I found out that I cannot test static methods using pure Mockito, so I need a PowerMockito user (right?).
I have a very simple class called Validate using this very simple method
public class Validate { public final static void stateNotNull( final Object object, final String message) { if (message == null) { throw new IllegalArgumentException("Exception message is a null object!"); } if (object == null) { throw new IllegalStateException(message); } }
Therefore, I need to verify that:
1) When I call this static method in the argument of the null message, IllegalArgumentException is called 2) When I call this static method on the argument of the null object, IllegalStateException is called
From what I got so far, I wrote this test:
import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.isNull; import org.junit.Before; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.testng.annotations.Test; @RunWith(PowerMockRunner.class) @PrepareForTest(Validate.class) public class ValidateTestCase { @Test(expectedExceptions = { IllegalStateException.class }) public void stateNotNullTest() throws Exception { PowerMockito.mockStatic(Validate.class); Validate mock = PowerMockito.mock(Validate.class); PowerMockito.doThrow(new IllegalStateException()) .when(mock) .stateNotNull(isNull(), anyString()); Validate.stateNotNull(null, null); } }
So, this suggests that I am mocking the Validate class, and I verify that when mock is called in this method with a null argument as an object and any string as a message, an IllegalStateException is thrown.
Now, I really do not understand. Why can't I just call this method directly, dropping all the voodoo magic around mocking this static class? It seems to me that if I do not call Validate.stateNotNull, that the test will pass anyway ... For what reason should I mock this?