在JUnit运行每个test...方法前都会调用setUp();并且在每个测试方法完成后,调用tearDown()。所以可以将设置和清理测试环境以及释放资源的工作放在这两个方法中,如打开以及关闭数据库联接等。

public class TestDB extends TestCase ...{
private Connection dbConn;

protected void setUp() ...{
dbConn = new Connection("oracle", 1521, "xxx", "xxx");
dbConn.connect();
}

protected void tearDown() ...{
dbConn.disconnect();
dbConn = null;
}

public void testXXX() ...{
...
}

public void testYYY() ...{
...
}
}

同样,针对整个test suite设置清理环境以及释放资源的工作也可以放在per-suite setup和per-suite tear-down中。为了实现per-suite setup和per-suite tear-down,需要将所需测试的suite包装进一个TestSetup对象中。
import junit.framework.*;
import junit.extensions.*;

public class TestClassTwo extends TestCase ...{

public TestClassTwo(String method) ...{
super(method);
}

public void testXXX() ...{
...
}

public void testYYY() ...{
...
}

public static Test suite() ...{
TestSuite suite = new TestSuite();
suite.addTest(new TestClassTwo("testXXX"));

TestSetup wrapper = new TestSetup(suite) ...{

protected void setUp() ...{
oneTimeSetUp();
}

protected void tearDown() ...{
oneTimeTearDown();
}
};
return wrapper;
}

public static void oneTimeSetUp() ...{
dbConn = new Connection("oracle", 1521, "xxx", "xxx");
dbConn.connect();
}

public static void oneTimeTearDown() ...{
dbConn.disconnect();
dbConn = null;
}
}


1556

被折叠的 条评论
为什么被折叠?



