JUnit4笔记(二)---JUnit的运行流程和常用注解

1、运行流程

新建一个JUnit Test Case,勾选红框中的四个方法:


这里写图片描述

完善各个已有的方法,并且添加两个test方法,test1()和test2()

public class JUnitFlow {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        System.out.println("this is BeforeClass...");
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        System.out.println("this is AfterClass...");
    }

    @Before
    public void setUp() throws Exception {
        System.out.println("this is Before...");
    }

    @After
    public void tearDown() throws Exception {
        System.out.println("this is After...");
    }

    @Test
    public void test1() {
        System.out.println("this is test1...");
    }

    @Test
    public void test2(){
        System.out.println("this is test2...");
    }

}

输出如下:


这里写图片描述

总结:
1、@BeforeClass修饰的方法会在所有方法被调用前被执行而且该方法是静态(static修饰)的,所以当测试类被加载后接着就会执行它,而且在内存中
它只会存在一份实例,它比较适合加载配置文件。
2、@AterClass所修饰的方法通常用来对资源的清理,如关闭数据库的连接,也是static修饰
3、@Before和@After会在每个测试方法的前后各执行一次

2、常用注解

主要有:
(1)@Test:将一个普通的方法修饰成为一个测试方法,有两个属性excepted和 timeout
excepted=XX.class可以捕获异常;
timeout可以设置测试方法运行的最长时间,可以方式呗测试方法死循环的时候导致系统崩溃
(2)@BeforeClass:它会在所有的方法运行前被执行,static修饰
(3)@AfterClass:它会在所有的方法运行结束后执行,static修饰
(4)@Before和@After
(5)@Ignore:所修饰的测试方法会被测试运行期忽略
(6)@RunWith:可以更改测试运行器
这里重点讲解@Test和@Ignore,@RunWith见我的下一篇博客
新建一个类Anotation:

public class AnotationTest {


    @Test(expected=ArithmeticException.class)
    public void testDivide() {
        assertEquals(8, new Calculator().divide(3, 0));
    }

    @Test(timeout=3000) //单位是毫秒
    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();
        }
    }

    @Ignore
    public void IgnoreTest()
    {
        System.out.println("能运行吗?");
    }
}

运行结果为:


这里写图片描述

说明:

          (1)在testDivide()方法的@Test注释中加了excepted属性,所以这个方法可以捕获到除数是0的异常,不会测试失败
          (2)对于timeout属性,在testWhile()方法中因为运行时间超出了设置的3000ms,所以显示测试失败,并且testWhile()的死循环也会结束;在testReadFile()方法中,因为运行时间小于设置时间,所以测试成功
          (3)可以看到@Ignore修饰的方法testIgnore()方法并没有被测试

猜你喜欢

转载自blog.csdn.net/u014473112/article/details/72289843