Junit is new framework designed for Java to perform unit testing. It is an Open source framework. Junit is an instance of xUnit architecture(A architecture designed for unit testing ). It helps the developers in designing and writing test cases. Junit also have a Graphical User Interface which allows developers to write test case easily and quickly. Unit testing means a small block of code, i.e a class. This allows developers to perform testing with developments. They can develop a class and write test case for that class to check they are on their intended goal or some deviation on their path.
A Test case a small fragment of code which checks another fragments of code(methods/function). There a different ways to write a test case. So when ever you required to check the accuracy of code, you must write the test case.
GGenerally test process is begin after completing the module, but Junit allows developers to code and test during development process.
Creating a simple Test Case
Consider a Simple calculate class given below
Calculate.java
package net.roseindia;
public class Calculate {
static public long sum(int x, int y) {
long c = x + y;
return c;
}
}
To write a test case of above given class make another test class which extends junit.framework.TestCase. The TestCase class extends Assert class and implements Test interface.
One thing is to note is the naming convention, the method name must be prefix a word 'test'. For example writing test case for sum method you must write 'testSum'.
Consider the given Test Case class Given Below
SampleInterfaceImp.java
package net.roseindia;
import junit.framework.TestCase;
public class TestCalculate extends TestCase {
int first;
int second;
long sum;
long methodResult;
@Override
protected void setUp() throws Exception {
// TODO Auto-generated method stub
// Initializing Values
first = 15;
second = 10;
//Setting Expected Value
sum = 25;
// Calculating Value from method
methodResult = Calculate.sum(first, second);
super.setUp();
}
public void testSum() {
// Testing Value
assertEquals("Method Tested ", methodResult, sum);
}
@Override
protected void tearDown() throws Exception {
// TODO Auto-generated method stub
super.tearDown();
}
}
Here setUp() and tearDown() method is given by the TestCase class. setUp() method is used for setting / initializing while tearDown() method is used for clean up.
The method assertEquals compares the expected value and method generated value.
When you will run the above code in eclipse you will see the following output.
|
|