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

<dependency>
	<groupId>org.mockito</groupId>
	<artifactId>mockito-core</artifactId>
	<version>2.18.3</version>
	<scope>test</scope>
</dependency>
<dependency>
	<groupId>org.assertj</groupId>
	<artifactId>assertj-core</artifactId>
	<version>3.10.0</version>
	<scope>test</scope>
</dependency>

Static Class

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

public final class MyStaticTest {
	public static String getString() {
		return "test";
	}
}

Imports

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
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.

@RunWith(PowerMockRunner.class)
@PrepareForTest({ MyStaticTest.class })
public class AppTestStatic {
	@Before
	public void setup() {
		MockitoAnnotations.initMocks(this);
		PowerMockito.mockStatic(MyStaticTest.class);
	}

	@Test
	public void myTest() {
		when(MyStaticTest.getString()).thenReturn("myTest");

		final String returnString = MyStaticTest.getString();

		assertThat(returnString).isEqualTo("myTest");
	}
}