Monday 2 July 2018

Junit: @Ignore: Ignoring tests

There are situations, where you want to ignore some tests from execution. You can do that by adding @Ignore annotation on a test case. Junit test runners report the number of ignored test cases along with the number of tests that ran and the number of tests that failed.

@Ignore
@Test
public void factorial_10_3628800() throws Exception {
                 
}

You can even specify the reason, why you are ignoring the test case by passing the details to @Ignore annotation.

@Ignore("Smae kind of test is already written")
@Test
public void factorial_10_3628800() throws Exception {
                 
}

Find the below working example.

Factorial.java

package com.sample.arithmetic;

public class Factorial {

 public long factorial(int num) throws Exception {
  if (num < 0) {
   throw new IllegalArgumentException("Factorial is not computed for negative numbers");
  }

  if(num > 10) {
   throw new Exception("Can't calculate factorial for big number");
  }
  
  long result = 1;

  for (int i = 2; i <= num; i++) {
   result *= i;
  }

  return result;
 }
}

FactorialTest.java
package com.sample.arithmetic;

import static org.junit.Assert.assertEquals;

import org.junit.Ignore;
import org.junit.Test;

/**
 * Test cases follow below naming convention. methodName_input_output format.
 * 
 * @author krishna
 *
 */
public class FactorialTest {

 @Test
 public void factorial_5_120() throws Exception {
  Factorial factorial = new Factorial();

  long actual = factorial.factorial(5);
  long expected = 120;

  assertEquals(expected, actual);
 }

 @Ignore("Smae kind of test is already written")
 @Test
 public void factorial_10_3628800() throws Exception {
  Factorial factorial = new Factorial();

  long actual = factorial.factorial(10);
  long expected = 3628800;

  assertEquals(expected, actual);
 }
}


When you ran FactorialTest.java in eclipse, you can able to see below kind of report.


As you observe above report, it is clearly telling that 1 test out of 2 is skipped.


Previous                                                 Next                                                 Home

No comments:

Post a Comment