1、测试失败的两种情况
*a、测试用例不是用来证明你是对的,而是用来证明你没有错*
*b、测试用例用来达到想要的预期结果,但对于逻辑错误无能为力。*
1.1 Failures:
a.failures代发:
package util;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class errorTest {
@Test
public void testAdd(){
assertEquals(5,new Calculate().add(3, 3));
}
}
b.结果:
1.2 Error:
a.error代码:
package util;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class errorTest {
@Test
public void testDivide(){
assertEquals(2,new Calculate().divide(6, 0));
}
}
b.结果:
总结:
a.Failure一般由单元测试使用的断言方法判断失败所引起的,这表示测试点发现了问题,就是说程序输出的结果和我们预期的不一样。
b.error是由代码异常引起的,它可以产生于测试代码本身的错误,也可以是被测试代码中的一个隐藏的bug。
2.运行流程
2.1新建一个JUnit test,加入四个方法,如下图:
2.2 内部代码如下:
package util;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class JUnitFlowTest {
@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、@AfterClass、@Before、@After是一定会被执行的代码段。
2、@BeforeClass修饰的方法会在所有方法被调用前执行;且该方法是静态的,所以当测试类被加载后接着就会运行它;且在内存中它只会存在一份实例,它比较适合加载配置文件。
3、@AfterClass所修饰的方法会在所有方法被调用后执行,通常用来对资源的清理,如关闭数据库的链接。
4、@Before和@After会在每个测试方法的前后各执行一次。
3.常用注解
1、我们前面已经了解过:
a. @Test: 将一个 普通的方法修饰成为一个测试方法
@Test(expected=XX.class):表示捕获并抛出一个异常
@Test(timeout=毫秒):表示对测试方法的运行时间进行限定
b.@BeforeClass: 他会在所有的方法运行前被执行,static修饰
c.@AfterClass 他会在所有方法运行结束后被执行,static修饰
d.@Before:会在每一个测试方法被运行前执行一次
e. @After 会在每个测试方法被运行后执行一次
2、下面我们演示一下两个新的注解:
a.@Ignore 所修饰的测试方法会被测试运行器忽略
package util;
import org.junit.*;
public class JUnitFlowTest {
@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");
}
@Ignore
@Test
public void test2(){
System.out.println("this is test2");
}
}
b.@RunWith: 可以修改测试运行器 org.junit.runner.Runner