I. Configure the environment
To use JUnit, you must first import the JUnit class library, right-click the project name, and select Properties.
Select Java build path, then select libraries, add library select JUnit to add
2. Compile the test code
Write a simple cat class as the tested Code. There are two methods:
public class Cat {public void run(){System.out.println(" Cat run ");}public void eat(){System.out.println(" Cat eat ");}}
Then write the test class cattest to test the cat class method:
public class CatTest {public void testRun(){Cat cat = new Cat();cat.run();}}
Add the @ test annotation to the test method of the cattest class.
public class CatTest {@Testpublic void testRun(){Cat cat = new Cat();cat.run();}}
Run the test code using juint
View the running result in the console dialog box at the bottom. The juint dialog box displays the test statistical result.
3. @ before and @ After annotations
public class CatTest {Cat cat;@Beforepublic void before(){System.out.println("before");cat = new Cat();}@Testpublic void testRun(){cat.run();}@Testpublic void testEat(){cat.eat();}@Afterpublic void after(){System.out.println("after");}}
The @ before annotation method runs once before each test method, and the @ After annotation method runs once after each test method.
@ Beforeclass and @ afterclass annotation methods run only once during test class generation and destruction, and their annotation methods must be static.
Iv. Assertions
Use the static method of the assert class to add assertions to the test method. If the assertion fails, the test fails.