Java: JUnit 4 /w PowerMock

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");
	}
}

 

Java: JUnit 4 Example

In this tutorial I will show you how to use JUnit 4 into your application. The next tutorial I will use this class with PowerMock.

Build Path

Ensure you have added JUnit 4 to your build path and that you are using Java 8.

Imports

import org.junit.Before;
import org.junit.Test;

Test Class

package ca.gaudreault.mytestapp;

import org.junit.Before;
import org.junit.Test;

public class AppTest {
	@Before
	public void setup() {
	}

	@Test
	public void myTest() {
	}
}

This was a very basic example of writing a unit test with JUnit 4. In future example I will build on this with PowerMock.