Sunday, 24 June 2018

Junit: Hello World program

In this post, I am going to explain, how can you test simple addition method using junit.

Arithmetic.java
package com.sample.arithmetic;

public class Arithmetic {

 public int add(int a, int b) {
  return a + b;
 }
}

ArithmeticTest.java
package com.sample.arithmetic;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class ArithmeticTest {

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

  int actualResult = obj1.add(10, 20);
  int expectedResult = 30;

  assertEquals(expectedResult, actualResult);
 }
}


Project structure looks like below.

Right click on ArithemticTest.java -> Run As -> Junit Test.


You can able to see below messages in junit window.




As you observe above window, it is showing that one test case ran and it is passed.

@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. 

assertEquals(expectedResult, actualResult);
Above statement throws an AssertionError, if expectedResult and actualResult are not equal.

How junit helps us to identify errors?
For example, if developer implements the add method wrongly like below.


package com.sample.arithmetic;

public class Arithmetic {

 public int add(int a, int b) {
  return a + b + b;
 }
}


When you ran the test case, it fails.


As you see the error message, test case expecting 30, but the actual result is 50. By reading the error message, developer can understand the problem and fix the test case.


Previous                                                 Next                                                 Home

No comments:

Post a Comment