TestNG - Esegui test JUnit

Ora che hai capito TestNG ei suoi vari test, devi essere preoccupato di come rifattorizzare il tuo codice JUnit esistente. Non c'è motivo di preoccuparsi, poiché TestNG fornisce un modo per passare da JUnit a TestNG al proprio ritmo. Puoi eseguire i tuoi casi di test JUnit esistenti utilizzando TestNG.

TestNG può riconoscere ed eseguire automaticamente i test JUnit, in modo da poter utilizzare TestNG come runner per tutti i test esistenti e scrivere nuovi test utilizzando TestNG. Tutto quello che devi fare è mettere la libreria JUnit sul classpath TestNG, in modo che possa trovare e usare le classi JUnit, cambiare il tuo test runner da JUnit a TestNG in Ant, e quindi eseguire TestNG in modalità "mista". In questo modo, puoi avere tutti i tuoi test nello stesso progetto, anche nello stesso pacchetto, e iniziare a utilizzare TestNG. Questo approccio consente inoltre di convertire i test JUnit esistenti in TestNG in modo incrementale.

Facciamo un esempio per dimostrare questa straordinaria capacità di TestNG.

Crea classe test case JUnit

Crea una classe java, che è una classe di test JUnit, TestJunit.java in C:\>TestNG_WORKSPACE.

import org.junit.Test;
import static org.testng.AssertJUnit.assertEquals;

public class TestJunit {
   @Test
   public void testAdd() {
      String str = "Junit testing using TestNG";
      AssertEquals("Junit testing using TestNG",str);
   }
}

Ora, scriviamo il testng.xml in C:\>TestNG_WORKSPACE, che conterrebbe il tag <suite> come segue:

<?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>

Per eseguire i casi di test JUnit, definire la proprietà junit = "true" come nell'xml precedente. La classe del test case JUnit TestJunit è definita nel nome della classe.

Per JUnit 4, TestNG utilizzerà il runner org.junit.runner.JUnitCore per eseguire i test.

Compila tutte le classi java usando javac.

C:\TestNG_WORKSPACE>javac TestJunit.java

Ora, esegui testng.xml, che eseguirà il test case JUnit come TestNG.

C:\TestNG_WORKSPACE>java -cp "C:\TestNG_WORKSPACE:C:\TestNG_WORKSPACE\lib\junit-4.11.jar" org.testng.TestNG testng.xml

Qui, abbiamo posizionato junit-4.11.jar in C: \ TestNG_WORKSPACE \ lib \ junit-4.11.jar.

Verifica l'output.

===============================================
   Converted JUnit suite

   Total tests run: 1, Failures: 0, Skips: 0
===============================================