Tuesday, September 3, 2013

JUnit – Ignore Test


JUnit – Ignore Test

Sometimes our code is not ready, but test case written to test. Such a situation that method/code will fail if run. The @Ignore annotation helps in this regards.

JUnit engine will just bypass the method which annotate as ignore.

Below simple example explain how the @ignore 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. IgnoreTest.java

import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;


public class IgnoreTest {

      TestJUnitMessageUtil messageUtil = new TestJUnitMessageUtil("Sanjeeva");

      @Ignore
      @Test
      public void printMessage(){
            Assert.assertEquals("Sanjeeva", messageUtil.printMessage());
      }

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

     /**
     * @param args
     */
     public static void main(String[] args) {

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

}