Thursday, October 2, 2014

JUnit testing

JUnit:

- Unit testing framework for Java programming language.
- It is important in test driven development.
- Promotes idea of first testing then coding
- Emphasis is on setting up test data for piece of code which can be tested first and then implemented.

Features:

- Open source framework for writing and running tests.
- Provides annotation to identify test methods
- Provides assertion for testing expected results
- Provides test runners for running tests.
- Allows to write code faster
- It is less complex and takes less time.
- Can be organized into test suites containing test cases and even other test suites
- Formal unit test case is characterized by known input and by an expected output.
- Known input should test precondition and expected output should test post condition.
- There must be at least two unit test cases for each requirement, one positive test and one negative test.
- If requirement has sub requirement, each sub requirement must have at least two test cases as positive and negative.

JUnit environment setup:

- System requirement: JDK 1.5 or above

1) Verify Java installation in your machine:
c:\>java -version

2) Set JAVA Environment
Set the environment variable JAVA_HOME to C:\Program Files\Java\jdk1.6.0_21

Append Java compiler location to System Path.
Append the string ;C:\Program Files\Java\jdk1.6.0_21\bin to the end of the system variable, Path.

3) Download JUnit Archive:
Download latest version of JUnit jar file from http://www.junit.org.

4) Set JUnit environment:
Set the environment variable JUNIT_HOME to C:\JUNIT

5) Set ClassPath Variable:
- Set the environment variable CLASSPATH to %CLASSPATH%;%JUNIT_HOME%\junit4.10.jar;.;

6) Test JUnit Setup:


Create a java class file name TestJunit in C:\ > JUNIT_WORKSPACE
   
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
   @Test
   public void testAdd() {
      String str= "Junit is working fine";
      assertEquals("Junit is working fine",str);
   }
}
Create a java class file name TestRunner in C:\ > JUNIT_WORKSPACE to execute Test case(s)
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}  

7. Verify the result.

Compile the classes using javac compiler as follows
C:\JUNIT_WORKSPACE>javac TestJunit.java TestRunner.java
Now run the Test Runner to see the result
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output.  true

What is JUnit Test Framework?

- JUnit is regression testing framework.to implement unit testing in Java.
- It can be easily integrated into Eclipse, Ant and Maven

Features:

- Fixtures
- Test suites
- Test runners
- JUnit classes

Fixtures:

- Fixed state of set of objects used as baseline for running tests.
- Purpose is to ensure that there is a well known and fixed environment in which tests are run so results are repeatable.
It includes:
- setUp() method which runs before every test invocation
- tearDown() method which runs after every test method.

Let's check one example:

import junit.framework.*;

public class JavaTest extends TestCase {
   protected int value1, value2;
   
   // assigning the values
   protected void setUp(){
      value1=3;
      value2=3;
   }

   // test method to add two values
   public void testAdd(){
      double result= value1 + value2;
      assertTrue(result == 6);
   }
}

Test suite means bundle a few unit test cases and run it together. In JUnit, both @RunWith and @Suite annotation are used to run the suite test. Here is an example which uses TestJunit1 & TestJunit2 test classes.

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

//JUnit Suite Test
@RunWith(Suite.class)
@Suite.SuiteClasses({ 
   TestJunit1.class ,TestJunit2.class
})
public class JunitTestSuite {
}
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;

public class TestJunit1 {

   String message = "Robert"; 
   MessageUtil messageUtil = new MessageUtil(message);
   
   @Test
   public void testPrintMessage() { 
      System.out.println("Inside testPrintMessage()");    
      assertEquals(message, messageUtil.printMessage());     
   }
}
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;

public class TestJunit2 {

   String message = "Robert"; 
   MessageUtil messageUtil = new MessageUtil(message);
 
   @Test
   public void testSalutationMessage() {
      System.out.println("Inside testSalutationMessage()");
      message = "Hi!" + "Robert";
      assertEquals(message,messageUtil.salutationMessage());
   }
}

Test runner is used for executing the test cases. Here is an example which assumes TestJunit test class already exists.
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}

JUnit classes

JUnit classes are important classes which is used in writing and testing JUnits. Some of the important classes are
  • Assert which contain a set of assert methods.
  • TestCase which contain a test case defines the fixture to run multiple tests.
  • TestResult which contain methods to collect the results of executing a test case.

Create a Class

  • Create a java class to be tested say MessageUtil.java in C:\ > JUNIT_WORKSPACE
/*
* This class prints the given message on console.
*/
public class MessageUtil {

   private String message;

   //Constructor
   //@param message to be printed
   public MessageUtil(String message){
      this.message = message;
   }
      
   // prints the message
   public String printMessage(){
      System.out.println(message);
      return message;
   }   
}  

Create Test Case Class

  • Create a java test class say TestJunit.java.
  • Add a test method testPrintMessage() to your test class.
  • Add an Annotaion @Test to method testPrintMessage().
  • Implement the test condition and check the condition using assertEquals API of Junit.
Create a java class file name TestJunit.java in C:\ > JUNIT_WORKSPACE
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
 
   String message = "Hello World"; 
   MessageUtil messageUtil = new MessageUtil(message);

   @Test
   public void testPrintMessage() {
      assertEquals(message,messageUtil.printMessage());
   }
}

Create Test Runner Class

  • Create a TestRunner java class.
  • Use runClasses method of JUnitCore class of JUnit to run test case of above created test class
  • Get the result of test cases run in Result Object
  • Get failure(s) using getFailures() methods of Result object
  • Get Success result using wasSuccessful() methods of Result object
Create a java class file name TestRunner.java in C:\ > JUNIT_WORKSPACE to execute Test case(s)
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}   
Compile the MessageUtil, Test case and Test Runner classes using javac
C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output.
Hello World
true
Now update TestJunit in C:\ > JUNIT_WORKSPACE so that test fails. Change the message string.
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
 
   String message = "Hello World"; 
   MessageUtil messageUtil = new MessageUtil(message);

   @Test
   public void testPrintMessage() {
      message = "New Word";
      assertEquals(message,messageUtil.printMessage());
   }
}
Let's keep rest of the classes as is, and try to run same Test Runner
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output.

No comments:

Post a Comment