Testing using TestNG

TestNG (Next Generation) is another testing framework that is similar to the JUnit 4 framework, but it has new functionalities such as grouping concept, and dependency testing. These have made testing easier and more powerful. It is designed to cover all the categories of tests, such as the unit test, the functional test, the integration test, and so on. TestNG also supports multi-threaded testing.

TestNG annotations

TestNG uses annotations; a few of them are listed in the following table:

Annotation

Import

Description

@Test

org.testng.annotations.Test

It marks the method as a test method

@BeforeMethod

org.testng.annotations.BeforeMethod

The annotated method will be executed before each @test annotated method

@AfterMethod

org.testng.annotations.AfterMethod

The annotated method will be executed after the execution of each and every @test annotated method

@BeforeClass

org.testng.annotations.BeforeClass

The annotated method will be executed only once before the first test method in the current class is invoked

@AfterClass

org.testng.annotations.AfterClass

The annotated method will be executed only once after the execution of all the @Test annotated methods of that class

@BeforeTest

org.testng.annotations.BeforeTest

The annotated method will be executed before any @Test annotated method belonging to that class is executed

@AfterTest

org.testng.annotations.AfterTest

The annotated method will be executed after any @Test annotated method belonging to the classes is executed

Example of TestNG

Refer to the link http://testng.org/doc/download.html to set up TestNG for your IDEs. Add TestNG JAR to your CLASSPATH to compile and run the test cases created for TestNG, as shown here:

package org.packt.Spring.chapter9.SpringTesting.Calculator;

import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class SimpleCalculatorTestNGTests {

   private SimpleCalculator simpleCalculator;

   @BeforeMethod
   public void beforeMethod() {
          simpleCalculator = new SimpleCalculatorImpl();
   }

   @Test
   public void verifyAdd() {
          long sum = simpleCalculator.add(3, 7);
          Assert.assertEquals(10, sum);
   }
}

You will see a progressive green bar if your test case passes:

Example of TestNG
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset