Sunday, 24 June 2018

Junit: @Test annotation

If you attach @Test annotation to a public void method, then junit runs this method as a test case. If the test case matches the expectations, then it will be passed, else it is failed. JUnit provides number of assert methods to match the actual result with expected result.

Arithmetic.java

package com.sample.arithmetic;

public class Arithmetic {

 public int divide(int a, int b) {
  if (b == 0) {
   throw new IllegalArgumentException("Division by zero is not supported");
  }

  return a / b;
 }
}

ArithmeticTest.java
package com.sample.arithmetic;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

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

 @Test
 public void divide_10By3_1() {
  Arithmetic obj1 = new Arithmetic();

  int actualResult = obj1.divide(10, 3);
  int expectedResult = 3;

  assertEquals(expectedResult, actualResult);
 }
}


@Test annotation also supports, two optional parameters.
a.   expected: Used to test the exceptions thrown by a method
b.   timeout: used to fail the test case, if it takes longer than the specified time.

In my later posts, I will give details examples of these parameters.



Previous                                                 Next                                                 Home

No comments:

Post a Comment