How to use junit testing in Eclipse:
1. First create a new project called JUnit_Test and write the test class Calculator.java
public?class?Calculator ?{
private?static?int?result;?//?Static variable, used to store running results
public?void?add(int?n)?{ p>
result?=?result?+?n;
}
public?void?substract(int?n)?{
result ?=?result?-?1;?//Bug:?The correct one should be ?result =result-n
}
public?void?multiply(int?n) ?{
}?//?This method has not been written yet
public?void?divide(int?n)?{
result?=?result ?/?n;
}
public?void?square(int?n)?{
result?=?n?*?n;< /p>
}
public?void?squareRoot(int?n)?{
for?(;?;)?;//Bug?:?Infinite loop
}
public?void?clear()?{?//?Clear the result to zero
result?=?0;
< p>}public?int?getResult()?{
return?result;
}
}
2. Introduce the JUnit4 unit test package into this project: right-click on the project and click "Properties", as shown in the figure:
3. In the pop-up properties window, first select " Java Build Path", then go to the upper right and select the "Libraries" tab, and then click the "Add Library..." button on the far right, as shown below:
Then select JUnit4 in the new pop-up dialog box and click OK, as shown in the picture above, the JUnit4 software package is included in our project.
4. Generate the JUnit test framework: Right-click the class in Eclipse's Package Explorer to pop up the menu and select "New a JUnit Test Case". As shown in the figure below:
5. In the pop-up dialog box, make the corresponding selections, as shown in the figure below:
6. After clicking "Next", the system will automatically List the methods contained in your class and select the method you want to test. In this example, we only test the four methods of "addition, subtraction, multiplication, and division".
As shown in the figure below:
7. The system will automatically generate a new class CalculatorTest with the following code:
public?class?CalculatorTest?{
private? static?Calculator?calculator?=?new?Calculator();
@Before
public?void?setUp()?throws?Exception?{
calculator.clear();
}
@Test
public?void?testAdd()?{
calculator.add( 2);
calculator.add(3);
assertEquals(5,?calculator.getResult());
}
@Test
public?void?testSubstract()?{
calculator.add(10);
calculator.substract(2);
assertEquals(8,?calculator.getResult());
}
@Ignore("Multiply()?Not?yet?implemented")
@Test
public?void?testMultiply()?{
}
@Test
public?void?testDivide ()?{
calculator.add(8);
calculator.divide(2);
assertEquals(4,?calculator.getResult()) ;
}
}
8. Run the test code: After modifying the above code, we right-click on the CalculatorTest class and select "Run As?" à?JUnit Test" to run our test, as shown below: