Four steps to TestNG nirvana

Getting started with TestNG couldn’t be easier! First, define a POJO– note that your disco POJO doesn’t need to extend anything specific:

public class HierarchyTest {

}

Next, define a tripping test, which can follow any naming pattern you see fit. The test’s accessibility modifier doesn’t matter either, man.

import java.util.Vector;         

public class HierarchyTest {   

 public void verifyHierarchyValue() throws Exception{
  Hierarchy tst = HierarchyBuilder.buildHierarchy(Vector.class);
  assert tst.getHierarchyClassNames().length == 2: "length wasn't 2";
 }
}

Incidentally, I usually declare that all my tests throw Exception unless I’m trying to verify a specific exception type.

Thirdly, add the @Test annotation. If your bag is Java 1.4, simply create a JavaDoc style comment in the form of @testng.test.

import java.util.Vector;
import org.testng.annotations.Test;

public class HierarchyTest {
 @Test
 public void verifyHierarchyValue() throws Exception{
  Hierarchy tst = HierarchyBuilder.buildHierarchy(Vector.class);
  assert tst.getHierarchyClassNames().length == 2: "length wasn't 2";
 }
}

Care to add a fixture? It’s as simple as creating a method to handle the set up logic and attaching the desired fixture granularity to it– in my case, I’d like this fixture to run once; hence, I’ll add a @BeforeMethod annotation to my method, man. Accordingly, if I wanted a tear down style method, I’d attach a @AfterMethod annotation to it. Java 1.4 users require a JavaDoc comment, such as @testng.before-method.

import java.util.Vector;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;

public class HierarchyTest {
 private Hierarchy tst;

 @BeforeClass
 private void fixture(){
  this.tst = HierarchyBuilder.buildHierarchy(Vector.class);
 }

 @Test
 public void verifyHierarchyValue() throws Exception{
  assert this.tst.getHierarchyClassNames().length == 2: "length wasn't 2";
 }
}

TestNG supports a myriad of runners from Ant to Eclipse to Maven to IntelliJ also. Running the newly created test via a desired mechanism, by the way, is step four. Was that easy or what, man?

Related odds and ends
 

One Response to “Four steps to TestNG nirvana”

  1. on 06 Nov 2006 at 3:55 pm Dan Allen

    First off, I love the new look!

    My only gripe is with the maven runner, which is currently crippled. I sure wish the apache maven team can get the fix out the door. The trouble is, right now it is necessary to use the testng.xml to run the tests with maven using the Java 5 annotations because of a bug in the surefire plugin. And the trouble with using the testng.xml file is that there is no easy way to tell it to run all the classes that match **/*Test*.java. Maven does the grunt work of identifying these files and passing them to TestNG, if the darn plugin worked.

Trackback this Post | Feed on comments to this Post

Leave a Reply