待测试类
package top.chgl16.junit; public class Calculate { 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; } }
Junit4 写的测试类
package test.top.chgl16.junit; import org.junit.Test; import org.junit.Before; import org.junit.After; import org.junit.BeforeClass; import org.junit.AfterClass; /** * Calculate Tester. * * @author <Authors name> * @since <pre>���� 24, 2018</pre> * @version 1.0 */ public class CalculateTest { @BeforeClass public static void beforeClass() throws Exception { System.out.println("This is beforeClass."); } @AfterClass public static void afterClass() throws Exception { System.out.println("This is afterClass."); } @Before public void before() throws Exception { System.out.println("This is before"); } @After public void after() throws Exception { System.out.println("This is after"); } /** * * Method: add(int a, int b) * */ @Test public void testAdd() throws Exception { //TODO: Test goes here... System.out.println("This is testAdd()"); } /** * * Method: subtract(int a, int b) * */ @Test public void testSubtract() throws Exception { //TODO: Test goes here... System.out.println("This is testSubtract"); } /** * * Method: multiply(int a, int b) * */ @Test public void testMultiply() throws Exception { //TODO: Test goes here... System.out.println("This is testMultiply"); } /** * * Method: divide(int a, int b) * */ @Test public void testDivide() throws Exception { //TODO: Test goes here... System.out.println("This is testDivide"); } }
运行测试代码(在非测试方法处鼠标右键运行)
This is beforeClass. This is before This is testAdd() This is after This is before This is testSubtract This is after This is before This is testDivide This is after This is before This is testMultiply This is after This is afterClass. Process finished with exit code 0
Junit4 常用注解有
@BeforeClass #修饰为静态方法,在所有方法前调用执行,全局就一次。在内存中只保存一份实例,适合测试加载配置文件
@AfterClass #对应@BeforeClass也修饰静态方法,在所有方法后调用执行,全局一次。适合清理资源回收关闭
@Before #在每个测试方法前调用,每个测试方法都调用一次
@After #对应@Before,每个测试方法后调用
@Test #注释待测试方法