Thursday, January 6, 2011

JUnit

JUnit is a framework to implement testing in JAVA. We can start testing with few steps using JUnit. First we have to download the latest version of JUnit, extract the zip to a directory and add path to CLASSPATH environment variable. Here I describe basic steps to implement testing with JUnit.

1. Import junit.framework subdirectory.

import junit.framework.*;

2. Extend TestCase to your simple java class to provide the ability to define our test methods.

public class MyClass extends TestCase {

3. Implement the constructor with a string argument that passes the name to super constructor as below. Every test have a name. By implementing this constructor, we can view which test gives an error from overall test results. 

public MyClass(String name) {
   super(name);


4. Define our own test method. This method is a simple test method to check whether mytest variable equals to 2.

public void testMyClassMethod(){
    int mytest=1;
    assertEquals("Mytest must be 1", mytest,1);
}   

No comments:

Post a Comment