TesNG annotations with example

Commonly used TestNG annotations


import java.util.*;
import org.testng.Assert;
import org.testng.annotations.*;

public class ExampleTestNG {

    private Collection testcoll;

    @BeforeClass
    public void onetimebeforeclass() {
        // one-time initialization code 
     System.out.println("@BeforeClass - onetimebeforeclass ");
    }

    @AfterClass
    public void onetimeafterclass () {
        // one-time cleanup code
     System.out.println("@AfterClass - onetimeafterclass ");
    }

    @BeforeMethod
    public void beforeeverymethod() {
        collection = new ArrayList();
        System.out.println("@BeforeMethod - beforeeverymethod ");
    }

    @AfterMethod
    public void aftereverymethod () {
        collection.clear();
        System.out.println("@AfterMethod - aftereverymethod ");
    }

    @Test
    public void testEmptyCollection() {
        Assert.assertEquals(collection.isEmpty(),true);
        System.out.println("@Test - testEmptyCollection");
    }

    @Test
    public void testOneItemCollection() {
        collection.add("itemA");
        Assert.assertEquals(collection.size(),1);
        System.out.println("@Test - testOneItemCollection");
    }
}

The result is below :

@BeforeClass - onetimebeforeclass
@BeforeMethod - beforeeverymethod
@Test - testEmptyCollection
@AfterMethod - aftereverymethod
@BeforeMethod - beforeeverymethod
@Test - testOneItemCollection
@AfterMethod - aftereverymethod
@AfterClass - onetimeafterclass
PASSED: testEmptyCollection
PASSED: testOneItemCollection