Monday, June 1, 2020

Unit Testing with JUnit - Tutorial

JUnit is a test framework which uses annotations to identify methods that specify a test. JUnit is an open source project hosted at Github.

3.2. How to define a test in JUnit?

A JUnit test is a method contained in a class which is only used for testing. This is called a Test class. To define that a certain method is a test method, annotate it with the @Test annotation.
This method executes the code under test. You use an assert method, provided by JUnit or another assert framework, to check an expected result versus the actual result. These method calls are typically called asserts or assert statements.
You should provide meaningful messages in assert statements. That makes it easier for the user to identify and fix the problem. This is especially true if someone looks at the problem, who did not write the code under test or the test code
package testing;                       
public class Calculator {
       public int add(int a, int b) {
             return (a + b);
       }
}
package testing;

import static org.junit.Assert.*;

import org.junit.Test;

public class CalculatorTest {

    @Test
    public void testAdd() {
        Calculator cal = new Calculator();
        int output = cal.add(2, 4);
        assertEquals(6, output);
        
    }

}

No comments:

Post a Comment