We create a class which implements the BasicCalculator interface, but doesn't really do anything at this point.
Create a class Calculator.java in your /src/org/confucius, like this:
package org.confucius;
public class Calculator implements BasicCalculator{
public int add(int a, int b) throws Exception {
return 0;
}
}
Now to write the tests.
Create a folder called 'test' in your HelloWorld project, at the same level as 'src'.
JUnit tests are always written in the /test folder by convention.
Now we need to tell Eclipse to consider this as a Java source folder. While our test code is not part of the application, Eclipse needs to treat it like Source code so that it can compile it.
To do this, R-click on your HelloWorld project, select New-->Source Folder, and give the folder name 'test'.
In the test folder, create subfolders org/confucius.
The package names for JUnit tests will always mirror the packages in the /src folder.
In /test/org/confucius, create a class TestCalculator.java, like this:
package org.confucius;
import junit.framework.TestCase;
public class TestCalculator extends TestCase {
public void testAddPositive(){
int a = 2;
int b = 3;
try {
BasicCalculator cal = new Calculator();
int sum = cal.add(a, b);
assertEquals(sum, 5);
}
catch (Exception e){
assertTrue(false);
}
}
public void testAddNegative(){
int a = -2;
int b = 3;
try {
BasicCalculator cal = new Calculator();
int sum = cal.add(a, b);
assertEquals(sum, 1);
}
catch (Exception e){
assertTrue(false);
}
}
public void testAddHuge(){
int a = 1000000000;
int b = 2000000000;
try {
BasicCalculator cal = new Calculator();
cal.add(a, b);
assertTrue(false);
}
catch (Exception e){
}
}
}
Let us understand this class.
It extends the JUnit TestCase class - this makes it a JUnit Test class.
All its methods start with the prefix 'test' - this is what tells the JUnit engine which methods to run as part of its test suite.
We have written 3 unit tests - first tests addition of positive numbers, second tests negative numbers and third tests numbers whose sums are out of range of int.
Note that for the third test, the test passes if an Exception is thrown. And fails if an Exception is not thrown. Because we want the Calculator to throw an Exception if the sum exceeds the maximum possible value of int.
We have written 3 unit tests. Ideally, we should write as many tests as possible to cover the full range of possibilities.
NOTE THAT we still haven't implemented the Calculator.java! We have written all our Tests before implementing Calculator.java - this is TEST DRIVEN DEVELOPMENT!
No comments:
Post a Comment