TestNG vs JUnit

 

Below is the detailed comparison between TestNG and JUnit, followed by Java code examples to demonstrate the key differences:


TestNG vs JUnit – Key Differences

FeatureTestNGJUnit (JUnit 4/5)
FrameworkOpen Source Java-based Testing frameworkOpen Source Testing framework
Annotations@BeforeSuite, @AfterClass, @Test, etc.@Before, @After, @Test, etc.
Dependency TestingSupports method dependencies using dependsOnMethodsNot directly supported
Supported TestingUnit Testing, Functional Testing, Integration Testing, end-to-end Testing, etc.Unit Testing
Suite ExecutionAllows XML-based suite executionUses test runners like @RunWith
Parallel ExecutionBuilt-in support with XML configRequires third-party tools
Order of TestsSupports ordering of test methods via a priority attributeDoes not support
GroupsSupports grouping of test No built-in group support
ReportsRich HTML/XML reportsBasic reports unless extended
Popular InSelenium & Test AutomationGeneral Unit Testing



TestNG Example

import org.testng.annotations.*;

public class TestNGExample {

    @BeforeClass
    public void setup() {
        System.out.println("TestNG: Setup before class");
    }

    @Test(priority = 1)
    public void loginTest() {
        System.out.println("TestNG: Executing login test");
    }

    @Test(priority = 2, dependsOnMethods = {"loginTest"})
    public void dashboardTest() {
        System.out.println("TestNG: Executing dashboard test");
    }

    @AfterClass
    public void teardown() {
        System.out.println("TestNG: Teardown after class");
    }
}




JUnit Example (JUnit 4)

import org.junit.*;

public class JUnitExample {

    @BeforeClass
    public static void setup() {
        System.out.println("JUnit: Setup before class");
    }

    @Test
    public void loginTest() {
        System.out.println("JUnit: Executing login test");
    }

    @Test
    public void dashboardTest() {
        System.out.println("JUnit: Executing dashboard test");
    }

    @AfterClass
    public static void teardown() {
        System.out.println("JUnit: Teardown after class");
    }
}

Note: JUnit doesn't support method dependency like TestNG.


Important Points:

  • Use TestNG for: complex test suites, method dependencies, grouping, parameterization, and Selenium testing.

  • Use JUnit for: standard unit testing, integration with Java frameworks, and simplicity.

No comments:

Post a Comment