首页 > 编程 > Java > 正文

Java单元测试工具——Junit

2019-11-08 18:45:05
字体:
来源:转载
供稿:网友

1.添加jar包,junit-4.11.jar和hamcrest-core-1.3.jar

package com.test.juint;import static org.junit.Assert.*;import org.junit.After;import org.junit.AfterClass;import org.junit.Before;import org.junit.BeforeClass;import org.junit.Ignore;import org.junit.Test;public class CalculateTest { /** * @Test 将一个普通的方法修饰成一个测试方法 * @Test(expected=xx.class) 忽略xx.class异常 * @Test(timeout=毫秒) 限定超时 * @Before 会在每个测试方法被运行前执行一次 * @BeforeClass 会在所有方法运行前被执行, static 修饰 * @After 会在每个测试方法被运行后执行一次 * @AfterClass 会在所有方法运行后被执行, static 修饰 * @Ignore 所修饰的测试方法会被测试运行器忽略 * RunWith 可以更改测试运行器 org.junit.runner.Runner */ @BeforeClass public static void setUpBeforeClass() throws Exception { System.out.PRintln("setUpBeforeClass"); } @AfterClass public static void tearDownAfterClass() throws Exception { System.out.println("tearDownAfterClass"); } @Before public void setUp() throws Exception { System.out.println("setUp"); } @After public void tearDown() throws Exception { System.out.println("tearDown"); } @Ignore("测试忽略!!") @Test public void testAdd(){ assertEquals(6, new Calculate().add(3, 3)); } @Test public void testSubtract(){ assertEquals(2, new Calculate().subtract(4, 2)); } @Test public void testMultiply(){ assertEquals(8, new Calculate().subtract(4, 2)); } @Test public void testDivide(){ assertEquals(2, new Calculate().divide(4, 2)); } @Ignore("忽略!!!") @Test(timeout=1) public void testWhile(){ while(true){ System.out.println("run forever"); } }}

编写测试套件,批量测试

package com.test.juint;import org.junit.runner.RunWith;import org.junit.runners.Suite;@RunWith(Suite.class)@Suite.SuiteClasses({CalculateTest.class, CalculateTest2.class, CalculateTest3.class})public class SuiteTest { /** * 1.测试套件就是组织测试类一起运行的 * * 写一个测试类的入口类,这个类里不包含其他的方法 * 更改测试运行器Suite.class * 将要测试的类作为数组传入到SuiteClasses({}) */}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表