Eclipse comes with the JUnit plug-in, which makes it easy to write test cases in a project without having to install them.
Add a JUnit library to your project
Before you can write test cases, you need to introduce JUnit first. Right-click on the project root, select Properties,java Build path,libraries,
Add Library, select JUnit:
Click Next to select the JUnit version, then finish is introduced.
Writing test Cases
Suppose you have the following classes:
package choon.test;
public class Calculate {
public int Add(int x,int y) {
return x + y;
}
}
You can write test cases as follows:
package choon.test;
import static org.junit.Assert.*;
import org.junit.Test;
public class Test1 {
@Test
public void test() {
Calculate calculate = new Calculate();
assertEquals(8, calculate.Add(3, 5));
}
}
Right-click Run as Junit test on the test method so that it runs:
, the green status bar indicates that the test passed, and if it is red, it does not pass.
Before and after tags
The method marked by before runs before each test case executes, and is run after each test case execution by the after-tagged method.
If you write the following test case:
package choon.test;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class Test1 {
@Before
public void setUp() {
System.out.println("---begin test---");
}
@Test
public void test() {
Calculate calculate = new Calculate();
assertEquals(8, calculate.Add(3, 5));
System.out.println("test case");
}
@After
public void tearDown() {
System.out.println("---end test---");
}
}
The following results will be executed:
It is important to write test cases, a bad test case is not a test and a waste of time, and a good test case can be very good to point out the problem in the code, to avoid greater trouble.