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 like this:
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));
}
}
, the green status bar indicates that the test passed, and if it is red, it does not pass.
This article references: www.cgzhw.com game Programming Network is a very good technical website.
Before and after tags
The methods marked by before are executed before each test case executes, and the after-tagged method executes after each test case executes.
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.