# Replace JUnit 4 Annotations with JUnit Jupiter

# Description

In JUnit Jupiter, annotations reside in org.junit.jupiter.api (opens new window), while in JUnit 4 annotations reside in org.junit (opens new window). This rule, replaces the following JUnit 4 annotations:

respectively with the JUnit Jupiter API (opens new window) alternatives:

By replacing each of these JUnit 4 annotations by the corresponding Jupiter alternatives, this rule promotes a stepwise transition to JUnit Jupiter.

Requirements

This rule requires the following library to be present:

  • junit:junit:4.13
  • org.junit.jupiter:junit-jupiter-api:5.0.0

# Benefits

Migrates JUnit 4 tests to JUnit 5.

# Tags

# Code Changes

# Replacing Imports and Annotations

Pre

package test.examples;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

public class ExampleTest {

	@Before
	public void beforeTestMethod() {
		// ..
	}

	@After
	public void afterTestMethod() {
		// ..
	}

	@BeforeClass
	public void beforeTestClass() {
		// ..
	}

	@AfterClass
	public void afterTestClass() {
		// ..
	}

	@Ignore
	@Test
	public void test() {
		// ..
	}
}

Post

package test.examples;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

public class ExampleTest {

	@BeforeEach
	public void beforeTestMethod() {
		// ..
	}

	@AfterEach
	public void afterTestMethod() {
		// ..
	}

	@BeforeAll
	public void beforeTestClass() {
		// ..
	}

	@AfterAll
	public void afterTestClass() {
		// ..
	}

	@Disabled
	@Test
	public void test() {
		// ..
	}
}

# Limitations

The transformation cannot be performed automatically if:

  • Any of the @Test annotations contains properties, e.g., @Test(timeout=...) or @Test(expected=...).
  • Any other JUnit 4 annotation, which is not mentioned above, is used explicitly or implicitly in the test class.

🛠️ Auto-refactor Available

You can auto refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID ReplaceJUnit4AnnotationsWithJupiter
First seen in jSparrow version 3.27.0
Minimum Java version 8
Remediation cost 15 min