PowerMock - mosinn/DOCS-n-Snippets-n-Steps GitHub Wiki

MUST read

https://github.com/powermock/powermock/wiki/Mockito(https://github.com/powermock/powermock/wiki/Mockito)

Snippets

> @RunWith(PowerMockRunner.class) > @PrepareForTest(Static.class)

  • Test level repeat repeat repeat for statics
@RunWith(PowerMockRunner.class) @PrepareForTest(Static.class) public class YourTestCase {
    @Test
    public void testMethodThatCallsStaticMethod() {
        // mock all the static methods in a class called "Static"
        PowerMockito.mockStatic(Static.class);
        // use Mockito to set up your expectation
        Mockito.when(Static.firstStaticMethod(param)).thenReturn(value);
        Mockito.when(Static.secondStaticMethod()).thenReturn(123);
        // execute your test
        classCallStaticMethodObj.execute();
        // Different from Mockito, always use PowerMockito.verifyStatic(Class) first
        // to start verifying behavior
        PowerMockito.verifyStatic(Static.class, Mockito.times(2));
        // IMPORTANT:  Call the static method you want to verify
        Static.firstStaticMethod(param);
        // IMPORTANT: You need to call verifyStatic(Class) per method verification,
        // so call verifyStatic(Class) again
        PowerMockito.verifyStatic(Static.class); // default times is once
        // Again call the static method which is being verified
        Static.secondStaticMethod();
        // Again, remember to call verifyStatic(Class)
        PowerMockito.verifyStatic(Static.class, Mockito.never());
        // And again call the static method.
        Static.thirdStaticMethod();
    }

}

Constructors have special way of being tested: PowerMockito.whenNew

⚠️ **GitHub.com Fallback** ⚠️