一,背景知识:ide
由前面的知识能够知道:测试
/*
* @Test:将一个普通方法修饰为一个测试方法
* @Test(exception=XXX.class)
* @Test(time=毫秒)
* @BeforeClass:它会在全部的测试方法前被执行,static修饰
* @AfterClass:它会在全部的测试方法后被执行,static修饰
* @Before:它会在每个测试方法前被执行一次
* @After:它会在每个测试方法后被执行一次
* @Ignore:省略
* @RunWith:修改运行器org。junit。runner。Runner
*
* */spa
其实@Test不只能够修饰一个普通方法为测试方法,还能够获取异常或者控制测试方法的执行时间线程
二,@Test的功能code
A,获取异常blog
B,控制测试代码执行时间it
A,获取异常代码展现io
1,获取异常,对异常的捕获:@Test(expected=XXX.class)class
1 package com.duo.util; 2 3 import static org.junit.Assert.*; 4 5 import org.junit.Test; 6 7 public class Anotation { 8 9 @Test(expected=ArithmeticException.class) 10 public void testDivide(){ 11 assertEquals(4, new Calculate().divide(12, 0)); 12 } 13 14 }
运行后结果:test
2,没有经过@Test(expected=ArithmeticException.class)注解时代码以及结果:
1 package com.duo.util; 2 3 import static org.junit.Assert.*; 4 5 import org.junit.Test; 6 7 public class Anotation { 8 9 @Test 10 public void testDivide(){ 11 assertEquals(4, new Calculate().divide(12, 0)); 12 } 13 14 }
运行结果:
B,控制测试代码执行时间,代码展现
测试方法控制@Test(timeout=毫秒),主要是针对代码中有循环代码的测试控制或者超时运行不符合预期的断定
1,咱们使用对一个死循环进行测试:
1 package com.duo.util; 2 3 import static org.junit.Assert.*; 4 5 import org.junit.Test; 6 7 public class Anotation { 8 9 @Test(timeout=2000) 10 public void testWhile(){ 11 while(true){ 12 System.out.println("run forever..."); 13 } 14 } 15 }
结果及时运行2秒后系统自动中止运行;
2,让当前线程运行2000毫秒,测试代码运行3000毫秒,符合预期结果
1 package com.duo.util; 2 3 import static org.junit.Assert.*; 4 5 import org.junit.Test; 6 7 public class Anotation { 8 9 @Test(timeout=3000) 10 public void testReadFile(){ 11 try { 12 Thread.sleep(2000); 13 } catch (InterruptedException e) { 14 // TODO Auto-generated catch block 15 e.printStackTrace(); 16 } 17 } 18 }
运行结果经过;
也能够经过调整测试时间比线程时间小,测试不符合预期的场景;
三,Ignore注解(该注解能够忽略当前的运行的方法,有时候改测试方法没有实现或者之后再实现)
1 package com.duo.util; 2 3 import static org.junit.Assert.*; 4 5 import org.junit.Ignore; 6 import org.junit.Test; 7 8 public class Anotation { 9 10 @Test(expected=ArithmeticException.class) 11 public void testDivide(){ 12 assertEquals(4, new Calculate().divide(12, 0)); 13 } 14 15 @Ignore 16 @Test(timeout=2000) 17 public void testWhile(){ 18 while(true){ 19 System.out.println("run forever..."); 20 } 21 } 22 23 @Test(timeout=3000) 24 public void testReadFile(){ 25 try { 26 Thread.sleep(2000); 27 } catch (InterruptedException e) { 28 // TODO Auto-generated catch block 29 e.printStackTrace(); 30 } 31 } 32 }
运行结果:
四,RunWith,能够修改测试运行器:org.junit.runner.Runner(后面使用到再解释)
五,断言:assert
断言assert的好多方法能够直接使用,主要是使用了静态导入:import static org.junit.Assert.*;