您的位置:首页 > 其它

junit 软件测试基础入门

2013-01-13 19:42 155 查看

 

import junit.framework.TestCase;

/**
* junit3 语法
* 1、必须继承TestCase
* 2、setUp()每个用例前执行一次
* 3、tearDown()在每个用例后执行一次
* 4、每个用例必须是void,必须以test开始
*
* @author emily
*
*/
public class Junit3Test extends TestCase {

@Override
protected void setUp() throws Exception {
// TODO Auto-generated method stub
/** setUp()每个用例前执行一次 */
System.out.println( "set up");
}

@Override
protected void tearDown() throws Exception {
// TODO Auto-generated method stub
/** tearDown()在每个用例后执行一次 */
System.out.println( "tear Down");
}

public void testMethod1() {
System.out.println( "testMethod1");
}

public void testMethod2() {
System.out.println( "testMethod2");
}

}
 
import java.util.Arrays;
import java.util.Collection;

import junit.framework.JUnit4TestCaseFacade;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
* junit3 juni4的差异:
* 1、JUnit 4使用org.junit.*包而JUnit 3.8使用的是junit.Framework.*
* 2、一个JUnit 4类中至少需要一个@Test注解
*
* junit4 语法:
* 注解的使用:
* 1、@Test 执行该用例,@Ignore不执行该用例
* 2、@Before @After 分别替代了3中的setUp tearDown
*
* @author emily
*
*/
@RunWith(Parameterized.class)
public class Junit4Test {

/**一个测试类只运行一次,在用例 <前>运行*/
@BeforeClass public static void beforclass(){
System. out.println("/**一个测试类只运行一次,在用例<前>运行*/" );
}

/**每个用例执行 <前>都跑一次*/
@Before public void init() {
System. out.println("/**每个用例执行都跑一次*/" );
}

/** @Test 执行该用例*/
@Test public void method1() {
System. out.println("testMethod1" );
}

/** @Ignore不执行该用例 */
@Ignore public void method2() {
System. out.println("testMethod2" );
}

/**限时测试 超过执行时间就抛出错误*/
@Test(timeout=1) public void compareArray(){
//比较数组 junit4 新加入功能
}

/**每个用例执行 <后>都跑一次*/
@After public void deinit() {
System. out.println("/**每个用例执行都跑一次*/" );
}

/**一个测试类只运行一次,在用例 <后>运行*/
@AfterClass public static void afterclass() {
System. out.println("/**一个测试类只运行一次,在用例<后>运行*/" );

}

//参数化测试用例,可以用于参数不停变换的测试用例场景
//参数的简洁性 在 JUnit 4 中创建参数测试只需要五个步骤:
//1. 创建一个不含参数的通用测试。
//2. 创建一个返回 Collection 类型的 static feeder 方法,并用 @Parameter 注释加以修饰。
//3. 为在步骤 1 中定义的通用方法所要求的参数类型创建类成员。
//4. 创建一个持有这些参数类型的构造函数,并把这些参数类型和步骤 3 中定义的类成员相应地联系起来。
//5. 通过 @RunWith 注释,指定测试用例和 Parameterized 类一起运行。
private String phrase;
private boolean match;

public Junit4Test(String phrase,boolean match) {
this.phrase = phrase;
this.match = match;
}

@Parameters
public static Collection regExValus() {
return Arrays.asList( new Object[][]{
{ "22101",true },{"221x1", false}
});
}

}
 
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
*
* @author emily
*
*/
//跑所有的测试集合,建立一个空类,直接配置注解就可以了
@RunWith(Suite.class)
@Suite.SuiteClasses ({ Junit4Test.class, Junit4Test. class })
//
public class AllTestRuns {

}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: