How to Invoke Junit Test Cases in TestNG?


TestNG can automatically recognize and run JUnit tests, so that you can use TestNG as a runner for all your existing tests and write new tests using TestNG. All you must do is to put JUnit library on the TestNG classpath, so it can find and use JUnit classes, change your test runner from JUnit to TestNG in Ant, and then run TestNG in "mixed" mode. This way, you can have all your tests in the same project, even in the same package, and start using TestNG. This approach also allows you to convert your existing JUnit tests to TestNG incrementally.

Let us have an example to demonstrate this amazing ability of TestNG.

Approach/Algorithm to solve this problem

  • Step 1: Create a junit classes − JunitTest

  • Step 2: Write a @Test method in the class.

  • Step 3: Now add the junit jar file in classpath.

  • Step 4: add testng.xml and mention junit class along with junit=true as mentioned in Program section.

  • Step 5: Now, run the testng.xml.

Example

The following code to show how to run junit test case in maven:

src/ NewTestngClass.java

import org.junit.Test;

public class JunitTest {
    @Test
    public void testcase1() {
        System.out.println("in test case 1 of junit");
    }
}  

testng.xml

This is a configuration file that is used to organize and run the junit/TestNG test cases.

It is very handy when limited tests are needed to execute rather than full suite.

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name = "Converted JUnit suite" >
   <test name = "JUnitTests" junit="true">
      <classes>
         <class name = "TestJunit" />
      </classes>
   </test>
</suite>

Output

===============================================
  Converted JUnit suite
  in test case 1 of junit
  Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================

Updated on: 18-Aug-2023

94 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements