First question is what is unit testing?
Well unit testing is a code written by a programmer to test a specific functionality of a program.
Now the question is how can we do this in java?
There are some libraries in java that helps unit testing. How ever the most popular and the common library used is the JUnit. Actually it is a framework that uses annotations to identify the test methods. Also one thing to remember is JUnit assumes that the tests can be conducted in an arbitrary order. That is the tests we write should not depend on each other.
Setting up JUnit.
You can download JUnit from http://www.junit.org/ and add the junit.jar to your project and classpath.
Using Junit
Create a java project using eclipse. Then right click on the project and create new->source folder and name it as test.
Now create a package inside the src folder and create a class named MyClass inside the package.
Enter the following code inside the MyClass.
return x * y;
}
Now right on the MyClass file and create new->JUnit Test. change the path from src to test in the screen you get after choosing JUnit Test in the menu. Name the file to MyClassTest. Now click next and choose the methods to be tested. click finish.
Now you will see a class called MyClassTest inside test folder. You will see something like below in the class.
@Test
public void testDivide() {
}
Now put the following code inside your testDivide method.
MyClass tester = new MyClass();
assertEquals("Result", 2, tester.divide(10, 5));
Now right click on the MyClassTest file and run as junit test. You will see a red bar as the result. This is because the result should be 2 but it returns 50. Now correct the code in divide method inside MyClass and rerun the unit test. You will see a green bar. That means the test is ok.
You can create a test suit also. That is you can select several tests and run all the selected methods.
Now select the Test classes and right click on it. Then new->other and then use Junit ->test suit. Fill the parameters according. After finishing, you will see the Test suit class is created. If you run the file, all the mentioned tests will be run.
Now lets see how you can run tests using your code.
create a class called MyTestRunner inside the test source folder. Then put the following code inside it.
public static void main(String[] args) {
Result result = JUnitCore.runClasses(MyClassTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
}
Now you will see if there are any errors in the test.
There are some annotations like @Test , @Before, @After, @AfterClass , @BeforeClass, @Ignore, @Test(timeout=100) , @Test(expected=Exception.class). Google and find what these annotations are used for.
No comments:
Post a Comment