Migrating from JUnit to TestNG: A Practical Step-by-Step Guide

Migrating from JUnit to TestNG: A Practical Step-by-Step Guide

Migrating a Java test suite from JUnit to TestNG is a common task — often triggered by a need for better parallel execution, more flexible data-driven testing, or explicit test suite management. The migration is manageable, but it has specific gotchas that can waste days if you don't know about them upfront.

This guide covers the complete migration path: annotation mapping, assertion differences, build tool configuration, and a phased approach that lets you migrate incrementally without breaking CI.

Before You Start: Reasons to Migrate (and Reasons Not To)

Good reasons to migrate to TestNG:

  • You need robust parallel test execution configured without per-test code changes
  • Your test suite uses Selenium WebDriver and you need the battle-tested TestNG integration
  • You need complex data-driven tests with @DataProvider across multiple classes
  • You need fine-grained suite management via testng.xml
  • You need @BeforeSuite / @AfterSuite hooks (JUnit 5 doesn't have these natively)
  • You want test dependencies (dependsOnMethods) with automatic downstream skipping

Reasons to reconsider:

  • Your project is Spring Boot — Spring's test support is tuned for JUnit 5
  • Your team is unfamiliar with testng.xml and doesn't need parallel execution
  • You want to use JUnit 5's powerful extension model
  • Your test suite is small and well-functioning — migration cost may not pay off

If you're not sure, read our TestNG vs JUnit 5 comparison first.

Step 1: Update Dependencies

From JUnit 4

Remove JUnit 4, add TestNG:

<!-- Remove this -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>

<!-- Add this -->
<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.8.0</version>
    <scope>test</scope>
</dependency>

From JUnit 5

<!-- Remove these -->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.10.0</version>
    <scope>test</scope>
</dependency>

<!-- Add TestNG -->
<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.8.0</version>
    <scope>test</scope>
</dependency>

Gradle

// Remove
testImplementation 'org.junit.jupiter:junit-jupiter:5.10.0'

// Add
testImplementation 'org.testng:testng:7.8.0'

test {
    useTestNG()
}

Step 2: Annotation Mapping

This is the mechanical core of the migration. The table below covers JUnit 4 → TestNG and JUnit 5 → TestNG.

JUnit 4 → TestNG

JUnit 4 TestNG Notes
@Test @Test Same name, different import
@Before @BeforeMethod Runs before each test method
@After @AfterMethod Runs after each test method
@BeforeClass @BeforeClass JUnit 4 requires static; TestNG does not
@AfterClass @AfterClass JUnit 4 requires static; TestNG does not
@Ignore @Test(enabled = false) Different mechanism
@Test(expected = Foo.class) @Test(expectedExceptions = Foo.class) Different attribute name
@Test(timeout = 1000) @Test(timeOut = 1000) Note the capital O
@RunWith(...) (no equivalent) TestNG uses listeners instead
@Rule (no equivalent) Use @BeforeMethod/@AfterMethod
@ClassRule (no equivalent) Use @BeforeClass/@AfterClass
@Parameterized @DataProvider Different model entirely

JUnit 5 → TestNG

JUnit 5 TestNG Notes
@Test @Test Same name, different import
@BeforeEach @BeforeMethod
@AfterEach @AfterMethod
@BeforeAll @BeforeClass JUnit 5 requires static; TestNG does not
@AfterAll @AfterClass JUnit 5 requires static; TestNG does not
@Disabled @Test(enabled = false)
@Tag("smoke") @Test(groups = {"smoke"})
@ParameterizedTest + @ValueSource @DataProvider Different model
@Timeout(value = 1, unit = SECONDS) @Test(timeOut = 1000) TestNG uses milliseconds
@ExtendWith(...) @Listeners(...) Different extension model
@TestInstance(PER_CLASS) (not needed) TestNG doesn't require static setup
@Nested (no equivalent) Restructure into separate classes

Import Changes

Every test file needs its imports updated:

// JUnit 4 — remove these
import org.junit.Test;
import org.junit.Before;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Ignore;

// JUnit 5 — remove these
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;

// TestNG — add these
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import org.testng.Assert;

For large codebases, do this with a script rather than manually:

find src/test -name "*.java" -exec sed -i \
  -e 's/import org.junit.jupiter.api.Test/import org.testng.annotations.Test/g' \
  -e 's/import org.junit.jupiter.api.BeforeEach/import org.testng.annotations.BeforeMethod/g' \
  -e 's/import org.junit.jupiter.api.AfterEach/import org.testng.annotations.AfterMethod/g' \
  -e 's/import org.junit.jupiter.api.BeforeAll/import org.testng.annotations.BeforeClass/g' \
  -e 's/import org.junit.jupiter.api.AfterAll/import org.testng.annotations.AfterClass/g' \
  -e 's/import org.junit.jupiter.api.Assertions/import org.testng.Assert/g' \
  -e 's/import org.junit.jupiter.api.Disabled/import org.testng.annotations.Test/g' \
  {} \;

Then do the annotation replacements similarly. Verify with compilation rather than trying to write a perfect script.

Step 3: Assertion Differences

This is the most common source of bugs post-migration.

Argument Order (Critical)

JUnit uses (expected, actual). TestNG uses (actual, expected). The arguments are reversed.

// JUnit 4/5 — expected first
assertEquals(42, result);
assertEquals("Alice", user.getName());

// TestNG — actual first
Assert.assertEquals(result, 42);
Assert.assertEquals(user.getName(), "Alice");

Wrong order doesn't cause compilation errors. Tests pass or fail the same way. But error messages become confusing:

// TestNG error message if you use JUnit order by mistake:
expected [result-value] but found [42]
// instead of the correct:
expected [42] but found [result-value]

Run a search across your test files and reverse all assertEquals argument pairs. This is tedious but necessary.

Static Import Changes

// JUnit 5
import static org.junit.jupiter.api.Assertions.*;
assertEquals(expected, actual);
assertThrows(Exception.class, () -> method());
assertAll(() -> assertEquals(a, b), () -> assertTrue(c));

// TestNG — not static
import org.testng.Assert;
Assert.assertEquals(actual, expected);
Assert.assertThrows(Exception.class, () -> method());

// TestNG soft assertions
SoftAssert soft = new SoftAssert();
soft.assertEquals(a, b);
soft.assertTrue(c);
soft.assertAll();

TestNG's assertAll equivalent is SoftAssert — you must create an instance, call assertions on it, then call assertAll() at the end. It's more explicit than JUnit 5's lambda-based assertAll.

Exception Testing

// JUnit 4
@Test(expected = IllegalArgumentException.class)
public void testBadInput() {
    service.process(null);
}

// JUnit 5
assertThrows(IllegalArgumentException.class, () -> service.process(null));

// TestNG — attribute on @Test
@Test(expectedExceptions = IllegalArgumentException.class,
      expectedExceptionsMessageRegExp = ".*cannot be null.*")
public void testBadInput() {
    service.process(null);
}

// TestNG — also works with assertThrows
Assert.assertThrows(IllegalArgumentException.class, () -> service.process(null));

Step 4: Parameterized Test Migration

This is the most significant structural change. JUnit's @ParameterizedTest and TestNG's @DataProvider have different models.

JUnit 5 @ValueSource → TestNG @DataProvider

// JUnit 5
@ParameterizedTest
@ValueSource(strings = {"", " ", "\t", "\n"})
void testBlankStrings(String input) {
    assertTrue(input.isBlank());
}

// TestNG
@DataProvider(name = "blankStrings")
public Object[][] blankStrings() {
    return new Object[][] {
        {""}, {" "}, {"\t"}, {"\n"}
    };
}

@Test(dataProvider = "blankStrings")
public void testBlankStrings(String input) {
    Assert.assertTrue(input.isBlank());
}

JUnit 5 @CsvSource → TestNG @DataProvider

// JUnit 5
@ParameterizedTest
@CsvSource({
    "Alice, alice@example.com, true",
    "Bob, not-an-email, false"
})
void testUserValidation(String name, String email, boolean expected) {
    assertEquals(expected, UserValidator.isValid(name, email));
}

// TestNG
@DataProvider(name = "userValidation")
public Object[][] userValidation() {
    return new Object[][] {
        {"Alice", "alice@example.com", true},
        {"Bob", "not-an-email", false}
    };
}

@Test(dataProvider = "userValidation")
public void testUserValidation(String name, String email, boolean expected) {
    Assert.assertEquals(UserValidator.isValid(name, email), expected);
}

JUnit 5 @MethodSource → TestNG @DataProvider

// JUnit 5
@ParameterizedTest
@MethodSource("provideUsers")
void testWithUsers(User user) {
    assertNotNull(user.getId());
}

static Stream<User> provideUsers() {
    return Stream.of(new User("Alice"), new User("Bob"));
}

// TestNG
@DataProvider(name = "users")
public Object[][] users() {
    return new Object[][] {
        {new User("Alice")},
        {new User("Bob")}
    };
}

@Test(dataProvider = "users")
public void testWithUsers(User user) {
    Assert.assertNotNull(user.getId());
}

Step 5: Migrate @Nested Classes

JUnit 5's @Nested classes have no TestNG equivalent. Flatten them:

// JUnit 5
class UserServiceTest {

    @Nested
    class WhenUserExists {
        @Test
        void testFind() { ... }
    }

    @Nested
    class WhenUserDoesNotExist {
        @Test
        void testFindReturnsNull() { ... }
    }
}

// TestNG — separate classes or use groups
public class UserServiceTest {

    @Test(groups = "userExists")
    public void testFind() { ... }

    @Test(groups = "userNotFound")
    public void testFindReturnsNull() { ... }
}

Or split into UserServiceExistsTest and UserServiceNotFoundTest.

Step 6: Create testng.xml

TestNG needs a suite configuration file. Start minimal:

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Test Suite">
    <test name="All Tests">
        <packages>
            <package name="com.example"/>
        </packages>
    </test>
</suite>

Then configure Maven Surefire to use it:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.1.2</version>
    <configuration>
        <suiteXmlFiles>
            <suiteXmlFile>testng.xml</suiteXmlFile>
        </suiteXmlFiles>
    </configuration>
</plugin>

Step 7: Handle JUnit Extensions

JUnit 5 extensions (@ExtendWith) have no direct equivalent. Map them:

JUnit 5 Extension TestNG Equivalent
@ExtendWith(MockitoExtension.class) Use MockitoAnnotations.openMocks(this) in @BeforeMethod
@ExtendWith(SpringExtension.class) Use AbstractTestNGSpringContextTests
Custom extensions TestNG ITestListener or @Listeners

Mockito with TestNG

// JUnit 5
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService;
}

// TestNG
public class UserServiceTest {
    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService;

    @BeforeMethod
    public void setup() {
        MockitoAnnotations.openMocks(this);
    }
}

Spring with TestNG

// JUnit 5
@SpringBootTest
class UserServiceTest { ... }

// TestNG
@SpringBootTest
public class UserServiceTest extends AbstractTestNGSpringContextTests { ... }

AbstractTestNGSpringContextTests is the TestNG equivalent of @ExtendWith(SpringExtension.class).

Phased Migration Strategy

Don't migrate all tests at once. Use this sequence:

  1. Add TestNG dependency without removing JUnit — both can coexist temporarily
  2. Create testng.xml listing only new test classes
  3. Migrate one package at a time — start with the simplest tests
  4. Run both suites in CI during the transition period
  5. Remove JUnit dependency once all tests are migrated and green

This keeps CI green throughout. You'll catch migration errors in isolated packages rather than across the entire suite.

Common Post-Migration Issues

Tests run in unexpected order: TestNG doesn't guarantee method order by default. Add @Test(priority = N) if order matters, or restructure to eliminate order dependencies.

Static setup methods fail: TestNG's @BeforeClass works on instance methods. If you copy JUnit 4's static methods directly, they still compile but behave differently. Remove the static keyword.

Wrong assertion argument order: As described above. This produces passing tests with misleading error messages. Write a test that intentionally fails and verify the message makes sense.

Missing @AfterMethod cleanup: JUnit 5's @AfterEach is equivalent to @AfterMethod, but teams sometimes forget to migrate cleanup methods. Always verify cleanup runs after each test.

How TestNG Fits Your Full Test Strategy

After migrating to TestNG, you'll have a more capable unit and integration test layer — better parallelism, more flexible data-driven tests, explicit suite management. But no unit testing framework covers the full picture.

For end-to-end coverage — validating that your application works correctly from a real user's perspective — you still need something at the browser and flow level. HelpMeTest complements TestNG by handling that layer in plain English, no code required. Your TestNG suite guards the business logic; HelpMeTest guards the user experience. With usage-based pricing at $0.003/test run, it's practical for teams that want 24/7 E2E coverage without building Selenium infrastructure.

Summary

The JUnit to TestNG migration involves five mechanical changes:

  1. Dependencies — swap the Maven/Gradle dependency
  2. Annotations — rename lifecycle annotations, update @Disabled to @Test(enabled=false)
  3. Assertions — reverse the argument order, update imports
  4. Parameterization — convert @ParameterizedTest to @DataProvider
  5. Extensions — replace @ExtendWith with @BeforeMethod setup or TestNG listeners

Do it incrementally. Keep CI green. Verify the argument order issue explicitly — it's the most common source of silent bugs post-migration. Once the migration is complete, invest in the capabilities that made it worthwhile: proper parallel configuration and data providers at scale.

Read more

Start now free