7/13/2017 5:26:38 AM
Viewed: 304
2/5/2013 4:59:47 PM
How to write a Unit Test?
  1. Define the expected and desired output for a normal case, with correct input.

  2. Now, implement the test by declaring a class, name it anything (Usually something like TestAddingModule), and add the testAdd method to it (i.e. like the one below) :

    • Write a method, and above it add the @Test annotation.
    • In the method, run your binary sum and assertEquals(expectedVal,calculatedVal).
    • Test your method by running it (in Eclipse, right click, select Run as → JUnit test).

      //for normal addition 
      public void testAdd1Plus1()
      int x = 1 ; int y = 1;
      assertEquals(2, myClass.add(x,y));
  3. Add other cases as desired.

    • Test that your binary sum does not throw a unexpected exception if there is an integer overflow.
    • Test that your method handles Null inputs gracefully (example below).

      //if you are using 0 as default for null, make sure your class works in that case.
      public void testAdd1Plus1()
      int y = 1;
      assertEquals(0, myClass.add(null,y));

For making unit test for your project, please follow these steps (I am using Eclipse in order to write this test):

1- Click on New -> Java Project.

Create Project

2- Write down your project name and click on finish.

Create Project

3- Write click on your project. Then, click on New -> Class.

Create Class

4- Write down your class name and click on finish.

Create Class

Then, complete the class like this:

public class Math {
int a, b;
Math(int a, int b) {
this.a = a;
this.b = b;
public int add() {
return a + b;

5- Click on File -> New -> JUnit Test Case.

Create JUnite Test

6- Check setUp() and click on finish. SetUp() will be the place that you initialize your test.

Check SetUp()

7- Click on OK.

Add JUnit

8- Here, I simply add 7 and 10. So, I expect the answer to be 17. Complete your test class like this:

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class MathTest {
Math math;
public void setUp() throws Exception {
math = new Math(7, 10);
public void testAdd() {
Assert.assertEquals(17, math.add());

9- Write click on your test class in package explorer and click on Run as -> JUnit Test.

Run JUnit Test

10- This is the result of the test.

Result of The Test

I hope it helps.

Gửi trả lời