注意在编写测试用例的时候,要保持测试用例的独立性
一个原则,每条单元测试用例都必须独立运行,不能依靠其他测试用例,或者不能按照什么顺序运行才可以。如果依靠其他测试用例的话,会给调试带来非常大的麻烦,所以这点一定要记住。
在junit4中引入注解,对方法执行进行一个说明。
import junit.framework.TestCase;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class caseTest extends TestCase {
String str1;
String str2;
String str3;
public caseTest(){}
@BeforeClass
public void beforeClass() {
System.out.println();
System.out.println("all methods not run");
}
@AfterClass
public void afterClass(){
System.out.println();
System.out.println("all method already run");
}
@Before
public void setUp() throws Exception {
str1 = "abc";
str2 = "111";
str3 = "abc";
System.out.println();
System.out.println("BEFORE test. conductor str1 str2 str3");
}
@After
public void tearDown() throws Exception {
str1 = null;
str2 = null;
str3 = null;
System.out.println("AFTER TEST DESOTRY STR1 STR3 STR2");
}
@Test
public void test1() {
System.out.println("check str is not null");
// 使用断言机制,来判断 测试结构是否符合预期
Assert.assertNotNull(str1);
}
@Test
public void test2() {
System.out.println("checke expect str3 and str1 value");
Assert.assertEquals(str3, str1);
}
public void test3() {
System.out.println("checke expect str2 and str1 value");
Assert.assertEquals(str3, str1);
}
}
在Junit4中因为引入的注解,所以对方法的名称没有限制,在所要实现方法的名称前,加上相应的注解
@Before 在每个方法执行前都要执行的一次的方法,一般对测试中要用的变量,环境的初始化保证每个测试的独立性。相当于SetUp()
@After 每个方法执行后都要执行一次的方法,一般是对初始变量和测试环境的恢复。 相当于Teardown()
@Test 标注出要测试的方法
@BeforeClass 在所有方法被执行前,要执行的方法。
@AfterClass 在所有方法被执行后, 再执行的方法。因此在整个类中,一般只被执行一次。
下面使用suite 来一起测试多个case用例。
import junit.framework.TestSuite;
import junit.textui.TestRunner;
public class AllTests {
public static void main(String[] args) {
Testsuite();
}
public static TestSuite Testsuite() {
//设置测试用例的名称
TestSuite suite = new TestSuite("MY TestSuite!");
// $JUnit-BEGIN$
//在suite中添加一个case ,这个case必须是继承Testcase
suite.addTestSuite(caseTest.class);
TestRunner.run(suite);
System.out.println(suite.getName());
// $JUnit-END$
return suite;
}
}