Tuesday, September 3, 2013

JUnit - Test suite


JUnit - Test suit

Test suite : bundle a few unit test cases and run it together.

* In JUnit, both @RunWith and @SuiteClasses annotation are used to run the suite test.

Below simple example explain how the test suite works in Junit.


1. TestJUnitMessageUtil.java

public class TestJUnitMessageUtil {

        private String message;
        /**
        * Constructor
        * @param message
        */
 
       public TestJUnitMessageUtil(String message){
              this.message = message;
       }

      //Print the message
      public String printMessage(){
              return this.message;
      }

      //Print the modified message
      public String printModifiedMessage(){
              return "Hi " + this.message;
      }
}

2. TestJUnit01.java

import org.junit.Assert;
import org.junit.Test;

public class TestJUnit01 {

          TestJUnitMessageUtil messageUtil = new TestJUnitMessageUtil("Sanjeeva");
 
          @Test
          public void testPrintMessage(){
                 Assert.assertEquals("Sanjeeva", messageUtil.printMessage());
          }
}

3. TestJUnit02.java

import org.junit.Assert;
import org.junit.Test;

public class TestJUnit02 {

           TestJUnitMessageUtil messageUtil = new TestJUnitMessageUtil("Sanjeeva");

           @Test
           public void testPrintMessage(){
                 Assert.assertEquals("Hi Sanjeeva", messageUtil.printModifiedMessage());
           }
}

4. TestSuite.java

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.RunWith;
import org.junit.runner.notification.Failure;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({TestJUnit01.class,TestJUnit02.class})
public class TestSuite {

        public static void main(String[] args) {

               Result result = JUnitCore.runClasses(TestSuite.class);
               for (Failure failure : result.getFailures()) {
                      System.out.println(failure.toString());
               }
               System.out.println(result.wasSuccessful());
      }
}