Junit is very useful for unit testing java code.
Let us understand with a simple example that will illustrate the basic concepts involved in testing with JUnit.
The Goal :
Creating a java file named Calculator.java which has a method named sum() which takes two int parameters
and return addition of these two numbers.
So here we have to check whether this method is functioning well in all the conditions or not.
Creating Calculator.java :
This class has sum method which takes two int parameters to add them and return it . Save and compile this file.
public class Calculator{
int sum(int num1,int num2){
return num1+num2;
}
}
Creating CalculatorTest.java :
To test that method sum() is working fine we need to check it.
For this we create another class named CalculatorTest. Save and compile this file.
Before proceeding further we should first have a look over JUnit coding convention.
Coding Convention :
1. Name of the test class must end with "Test".
2. Name of the method must begin with "test".
3. Return type of a test method must be void.
4. Test method must not throw any exception.
5. Test method must not have any parameter.
In our example, the class name which we are going to test is "Calculator" so we have created class "CalculatorTest" here.
Let us write the test case.