1. Create a new project, named Junittest, first write a target class calculator
Package com.mengdd.junit;
public class Calculator
{
public int Add (int a, int b)
{
return a + B;
}
public int subtract (int a, int b)
{
return a-B;
}
public int multiply (int a, int b)
{
return a * b;
}
public int divide (int a, int b)
{
return a/b;
}
}
2. Then in order to use JUnit, you need to join the library:
Right-click on the project properties-> left Java Build path-> tag Libraries->add Library ...
Add JUnit
3. Create a test class
4. Test Class Code writing
Note that the test class must inherit from the TestCase class.
Write the following code :
Package com.mengdd.junit;
import junit.framework.TestCase;
{
public void Testadd ()
Calculator Calculator = new Calculator ();
int result = Calculator.add (1, 2);
//return result of Judgment method
}
public void Testsubtract ()
Calculator Calculator = new Calculator ();
int result = Calculator.subtract (1, 2);
//return result of Judgment method
public void testmultiply ()
{
Calculator Calculator = new Calculator ();
int result = Calculator.multiply (2, 3);
The return result of the Judgment method
Assert.assertequals (6, result);//The first parameter is expected, the second argument is the value to validate
}
public void Testdivide ()
{
Calculator Calculator = new Calculator ();
int result = Calculator.divide (12, 3);
The return result of the Judgment method
Assert.assertequals (4, result);//The first parameter is expected, the second argument is the value to validate
}
}
Run: Right-Select the class, run As->junit Test
The results are as follows:
Third time job