企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] # junit4注解 ~~~ /* * @Test:将一个普通方法修饰为一个测试方法 * @Test(exception=XXX.class) * @Test(time=毫秒) * @BeforeClass:它会在所有的测试方法前被执行,static修饰 * @AfterClass:它会在所有的测试方法后被执行,static修饰 * @Before:它会在每一个测试方法前被执行一次 * @After:它会在每一个测试方法后被执行一次 * @Ignore:省略 * @RunWith:修改运行器org。junit。runner。Runner * * */ ~~~ 其实@Test不仅可以修饰一个普通方法为测试方法,还可以获取异常或者控制测试方法的执行时间 ## @Test的功能 获取异常 控制测试代码执行时间 **获取异常代码展示** 1. 获取异常,对异常的捕获:@Test(expected=XXX.class) ~~~ package com.duo.util; import static org.junit.Assert.*; import org.junit.Test; public class Anotation { @Test(expected=ArithmeticException.class) public void testDivide(){ assertEquals(4, new Calculate().divide(12, 0)); } } ~~~ 2. 没有通过@Test(expected=ArithmeticException.class)注解: ~~~ package com.duo.util; import static org.junit.Assert.*; import org.junit.Test; public class Anotation { @Test public void testDivide(){ assertEquals(4, new Calculate().divide(12, 0)); } } ~~~ **控制测试代码执行时间** 测试方法控制@Test(timeout=毫秒),主要是针对代码中有循环代码的测试控制或者超时运行不符合预期的判定 1. 我们使用对一个死循环进行测试: ~~~ package com.duo.util; import static org.junit.Assert.*; import org.junit.Test; public class Anotation { @Test(timeout=2000) public void testWhile(){ while(true){ System.out.println("run forever..."); } } } ~~~ 结果及时运行2秒后系统自动停止运行; 2. 让当前线程运行2000毫秒,测试代码运行3000毫秒,符合预期结果 ~~~ package com.duo.util; import static org.junit.Assert.*; import org.junit.Test; public class Anotation { @Test(timeout=3000) public void testReadFile(){ try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ~~~ 运行结果通过; 也可以通过调整测试时间比线程时间小,测试不符合预期的场景; ## Ignore注解 该注解可以忽略当前的运行的方法,有时候改测试方法没有实现或者以后再实现 ~~~ package com.duo.util; import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Test; public class Anotation { @Test(expected=ArithmeticException.class) public void testDivide(){ assertEquals(4, new Calculate().divide(12, 0)); } @Ignore @Test(timeout=2000) public void testWhile(){ while(true){ System.out.println("run forever..."); } } @Test(timeout=3000) public void testReadFile(){ try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ~~~ ## RunWith 可以修改测试运行器:org.junit.runner.Runner ## 断言:assert 断言assert的好多方法可以直接使用,主要是使用了静态导入:`import static org.junit.Assert.*;`