JUnit vs. TestNG: Understanding the Key Differences With Examples
Azher Iqbal
Sr. SQAE | Automation Specialist | Java | .NET | Selenium WebDriver | Cypress | BDD | PlayWritght | API Testing | Azure DevOps | Appium
Both JUnit and TestNG are popular frameworks in the Java ecosystem used for writing and running repeatable automated tests. Though they share some commonalities, there are key differences that set them apart.
JUnit:
Annotation-Based: JUnit favours simplicity with a streamlined approach. Use @Test for any test method.
import org.junit.Test;
import static org.junit.Assert.*;
public class SampleTest {
@Test
public void testAddition() {
assertEquals(2, 1 + 1);
}
}
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({SampleTest.class})
public class AllTests {
// This class remains empty, it is used only as a holder for the above annotations
}
TestNG:
Flexibility and Configuration: TestNG offers more advanced features like grouping, sequencing, and parameterizing tests using testng.xml.
领英推荐
<!-- testng.xml -->
<suite name="SampleSuite">
<test name="SampleTestGroup">
<classes>
<class name="SampleTest"/>
</classes>
</test>
</suite>
Annotations with Attributes: TestNG extends the concept of annotations by adding attributes like dependsOnMethods, timeOut, and dataProvider.
import org.testng.annotations.Test;
public class SampleTest {
@Test(timeOut = 1000)
public void testTimeSensitiveOperation() {
// code that should complete within 1000ms
}
@Test(dependsOnMethods = {"testTimeSensitiveOperation"})
public void testDependentMethod() {
// code that depends on the successful execution of testTimeSensitiveOperation
}
}
Built-in Data Providers: TestNG has built-in support for data-driven testing using @DataProvider.
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
public class DataDrivenSampleTest {
@DataProvider(name = "additionProvider")
public Object[][] createAdditionData() {
return new Object[][] {
{ 1, 1, 2 },
{ 2, 3, 5 },
};
}
@Test(dataProvider = "additionProvider")
public void testAddition(int a, int b, int expected) {
assertEquals(expected, a + b);
}
}
JUnit is streamlined and ideal for simpler use cases, while TestNG offers more configuration control and advanced features such as parameterized testing and dependencies between tests. The choice between JUnit and TestNG will often depend on specific project requirements and the preference for certain features