Junit4与Junit3的区别
1:在Junit3中需要继承TestCase类,但在Junit4中不需要
2:Junit3中需要重写TestCase中的setUp和tearDown方法,而在Junit4中,只需要在方法的前面加上@Before,@After
3:Junit3中测试方法前面要用“test”前缀,而Junit4则没有限制
Junit4的一些规范:
1.测试方法必须使用@Test进行修饰
2.测试方法必须使用public void进行修饰,不能带有任何的参数
3.新建一个源码目录来存放我们的测试代码
4.测试类的包应该和被测试类保持一致
5.测试单元中的每个方法必须可以独立测试,测试方法间不能有任何的依赖关系
Junit测试失败的两种情况:
1.(Failure)结果值跟预期值不一致
2.(error)测试代码的异常
另外,测试用例不是用来证明你是对的,对于逻辑上的错误是无能为力的
Junit运行流程:
1.@BeforeClass修饰的方法会在所有的方法被调用前执行而且方法是静态的,所以当测试类被加载后接着就会运行它,而且在内存中它只会存在一份实例,他比较适合加载配置文件。
2.@AfterClass所修饰的方法通常用来对资源的清理,如关闭数据库的链接
3.@Before和@After会在每个测试方法的前后各执行一次
Junit中常用注解:
1.@Test:将一个普通方法修饰为一个测试方法
@Test(expected=XX.class)预期的异常
@Test(timeout=毫秒)测试性能问题
2.@BeforeClass:他会在所有的方法运行前被执行,static修饰
3.@AfterClass:他会在所有的方法运行结束后被执行,static修饰
4.@Before:他会在每一个测试方法被执行前执行一次
5.@After:他会在每一个测试方法执行后被执行一次
6.@Ignore:所修饰的测试方法会被测试运行器忽略
7.@RunWith:可以更改测试运行器org.junit.runner.Runner
Junt4中的测试套件:
--测试套件就是组织测试类一起运行的
--写一个作为测试套件的入口类,这个类中不包含其他的方法
--更改测试运行器Suit.class
--将要测试的类作为数组传入到Suit,suitClasses({})--代码:
@RunWith(Suite.class)
@Suite.SuiteClasses({CaculatorTest.class})
public class SuiteTest {
}
Junit参数化设置:
1.更改默认的测试运行器为RunWith(Parameterized.class)
2.声明变量来存放预期值和结果值
3.声明一个返回值为Collection的公共的静态方法,并使用@Parameters进行修饰
4.为测试声明一个带有参数的公有构造函数,并在其中为之声明变量赋值
1 import static org.junit.Assert.*; 2 3 import java.util.Arrays; 4 import java.util.Collection; 5 6 import org.junit.Test; 7 import org.junit.runner.RunWith; 8 import org.junit.runners.Parameterized; 9 import org.junit.runners.Parameterized.Parameters; 10 11 import com.imooc.demo.JunitTest; 12 13 @RunWith(Parameterized.class) 14 public class ParameterTest { 15 int expected = 0; 16 int input1 = 0; 17 int input2 = 0; 18 @Parameters 19 public static Collection<Object[]> test(){ 20 21 return Arrays.asList(new Object[][]{ 22 {3,1,2}, 23 {4,2,2} 24 }); 25 } 26 public ParameterTest(int expected,int input1,int input2){ 27 this.expected = expected; 28 this.input1 = input1; 29 this.input2 = input2; 30 31 } 32 @Test 33 public void testAdd(){ 34 assertEquals(expected, new JunitTest().add(input1, input2)); 35 } 36 37 }
原文:http://www.cnblogs.com/zhuanghaoran/p/5269433.html