I have written test cases for testing a function in class Main
, called functionMain()
. I have seen people using PowerMockito to test static functions in the class Main
which is under test.
But in my case, functionMain()
is using a static function from another class called Branch
called staticBranchFunction()
.
I want to mock staticBranchFunction()
inside the tests for the Main
class.
This main function actually has calls to static functions from different classes Branch1
, Branch2
etc.
Please help.
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.times;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.verifyStatic;
@RunWith(PowerMockRunner.class)
@PrepareForTest({Boom.class})
public class DocTest {
public String boomWrapper() {
return Boom.detonate();
}
@Test
public void testBoom() {
mockStatic(Boom.class);
when(Boom.detonate()).thenReturn("defused");
String actual = boomWrapper();
verifyStatic(Boom.class, times(1));
Boom.detonate();
assertEquals("defused", actual);
}
}
class Boom {
private static final String BOOM = "Boom!";
public static String detonate() {
return BOOM;
}
}
junit:junit:4.12
org.mockito:mockito-core:2.13.0
org.powermock:powermock-module-junit4:2.0.0-beta.5
org.powermock:powermock-api-mockito2:2.0.0-beta.5
For more supported versions, please read: Mockito + PowerMock, other supported frameworks Requirements:
@PrepareForTest({Boom.class})
separate by comma.PowerMockito.mockStatic(Boom.class)
separate by comma.Mockito.when(Boom.detonate()).thenReturn("defused")
PowerMockito.verifyStatic(Boom.class, Mockito.times(1)); Boom.detonate();
Important: You need to call PowerMockito.verifyStatic(Boom.class)
per method verification.More details on PowerMock wiki.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments