Junit4学习(四)Junit4常用注解

时间:2022-06-23 05:08:38

一,背景知识:

由前面的知识可以知道:

    /*
     * @Test:将一个普通方法修饰为一个测试方法
     *   @Test(exception=XXX.class)
     *   @Test(time=毫秒)
     * @BeforeClass:它会在所有的测试方法前被执行,static修饰
     * @AfterClass:它会在所有的测试方法后被执行,static修饰
     * @Before:它会在每一个测试方法前被执行一次
     * @After:它会在每一个测试方法后被执行一次
     * @Ignore:省略
     * @RunWith:修改运行器org。junit。runner。Runner
     *
     * */

 

其实@Test不仅可以修饰一个普通方法为测试方法,还可以获取异常或者控制测试方法的执行时间

 

二,@Test的功能

A,获取异常

B,控制测试代码执行时间

 

 

A,获取异常代码展示

1,获取异常,对异常的捕获:@Test(expected=XXX.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 }

运行后结果:

Junit4学习(四)Junit4常用注解

 

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 }

运行结果:

Junit4学习(四)Junit4常用注解

 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 }

运行结果:

Junit4学习(四)Junit4常用注解

四,RunWith,可以修改测试运行器:org.junit.runner.Runner(后面使用到再解释)

五,断言:assert

断言assert的好多方法可以直接使用,主要是使用了静态导入:import static org.junit.Assert.*;