当前位置:   article > 正文

Junit单元测试_@ignore作用

@ignore作用
单元测试

作用:
在写完代码的时候,测试写好的程序是否存在bug。
与一般测试的区别:
一般测试(main方法测试):

public class T {
    public int add(int x, int y) {
        return x + y;
    }

    public static void main(String[] args) {
        System.out.println(new T().add(1, 2));
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

存在问题:

  1. 不能多个函数多个类一起运行,这个在需要测试的方法非常多的时候很不方便
  2. 大多数需要人为观察输入输出是否正确

使用Junit

import org.junit.*;
import static org.junit.Assert.*;
public class TTest {
    @Test
    public void add() {
        int add = new T().add(1, 2);
        assertEquals(3, add);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

keeps the bar green,to keep the code clean.

这句话表示绿色为测试通过:
测试通过
如果测试失败为红色(例如将结果改为4):

测试失败

Junit中方法

assertXxx类型的函数一般用来测试是否满足条件
如:assertEquals(long expected, long actual)测试expectedactual是否相等,如上面的例子所示。
带有message参数的重载
查看文档我们会发现,有很多带有message参数函数重载,这个参数的作用是在测试失败的时候打印的信息。
重载
如下:
测试message
assertThat
assertThat接受两个参数,使我们可以以英语语法的形式来达到我们想要的测试效果了,例如可以使用下面代码代替刚才的assertEquals:

import org.junit.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
public class TTest {
    @Test
    public void add() {
        int add = new T().add(1, 2);
        assertThat(add, is(3));
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
注解

@Test表示这个方法是一个测试方法,有两个参数,expected表示期望抛出什么异常,timeout表示程序的最长运行时间,超过指定的时间就会测试失败(单位是毫秒)。
@Test注解
@Ignore表示被忽略的测试方法,加上该注解之后这个方法不会被执行
@Before和@After表示在每一次执行测试方法的前后执行
@BeforeClass和@AfterClass分别在类初始化之前执行,所以必须为静态方法。用于加载配置文件,连接数据库等。

package com.qianyu;

import org.junit.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
public class TTest {
    @BeforeClass
    public static void beforeClass() {
        System.out.println("TTest.beforeClass");
    }

    @Before
    public void before() {
        System.out.println("TTest.before");
    }

    @Test
    public void add() {
        assertThat(new T().add(1, 2), equalTo(3));
        System.out.println("TTest.add");
    }

    @Test
    public void add2() {
        assertThat(new T().add(2, 2), equalTo(4));
        System.out.println("TTest.add2");
    }

    @Ignore
    public void ignore() {
        System.out.println("TTest.ignore");
    }

    @After
    public void after() {
        System.out.println("TTest.after");
    }

    @AfterClass
    public static void afterClass() {
        System.out.println("TTest.afterClass");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

运行结果:
测试结果

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
  

闽ICP备14008679号