Java: JUnit 4 /w PowerMock

(Last Updated On: )

In this tutorial I will show you how to use JUnit 4 with PowerMock for mocking Static classes into your application. If you have not already done so follow JUnit 4 tutorial.

POM.xml

  1. <dependency>
  2. <groupId>org.mockito</groupId>
  3. <artifactId>mockito-core</artifactId>
  4. <version>2.18.3</version>
  5. <scope>test</scope>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.assertj</groupId>
  9. <artifactId>assertj-core</artifactId>
  10. <version>3.10.0</version>
  11. <scope>test</scope>
  12. </dependency>

Static Class

We will create this class to use for our static testing.

  1. public final class MyStaticTest {
  2. public static String getString() {
  3. return "test";
  4. }
  5. }

Imports

  1. import static org.assertj.core.api.Assertions.assertThat;
  2. import static org.mockito.Mockito.when;
  3.  
  4. import org.junit.Before;
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.mockito.MockitoAnnotations;
  8. import org.powermock.api.mockito.PowerMockito;
  9. import org.powermock.core.classloader.annotations.PrepareForTest;
  10. import org.powermock.modules.junit4.PowerMockRunner;

Test Class

Now we can run our test with PowerMock and mock our static classes methods as you can see from the below.

  1. @RunWith(PowerMockRunner.class)
  2. @PrepareForTest({ MyStaticTest.class })
  3. public class AppTestStatic {
  4. @Before
  5. public void setup() {
  6. MockitoAnnotations.initMocks(this);
  7. PowerMockito.mockStatic(MyStaticTest.class);
  8. }
  9.  
  10. @Test
  11. public void myTest() {
  12. when(MyStaticTest.getString()).thenReturn("myTest");
  13.  
  14. final String returnString = MyStaticTest.getString();
  15.  
  16. assertThat(returnString).isEqualTo("myTest");
  17. }
  18. }