【发布时间】:2014-01-10 20:31:14
【问题描述】:
我有点难以理解使用ExternalResource 的好处。 documentation 和其他帖子 (How Junit @Rule works?) 都暗示能够在类内的测试之间共享代码和/或在测试类之间共享代码。
我正在尝试将ExternalResource 用于功能/集成测试中的数据库连接,但我不知道如何跨类共享该连接。事实上,在这种情况下,我并没有真正看到 @Before/@After 的好处。我是在错误地使用它还是我错过了什么?
public class some_IntegrationTest {
private static String id;
Connection connection = null;
//...
@Rule
public ExternalResource DBConnectionResource = new ExternalResource() {
@Override
protected void before() throws SQLException {
connection = DbUtil.openConnection();
}
@Override
protected void after() {
DbUtil.closeConnection(connection);
}
};
@BeforeClass
public static void setUpClass() throws SQLException {
System.out.println("@BeforeClass setUpClass");
cleanup(id);
}
//I want to do something like this
@Test
public void test01() {
cleanupData(connection, id);
// do stuff...
}
@Test
public void test02() {
cleanupTnxLog(connection, id);
// do stuff...
}
//...
private static void cleanup(String id) throws SQLException {
LOGGER.info("Cleaning up records");
Connection connection = null;
try {
connection = DbUtil.openConnection();
cleanupData(connection, id);
cleanupTnxLog(connection, id);
} finally {
DbUtil.closeConnection(connection);
}
}
private static void cleanupData(Connection connection, String id)
throws SQLException {
dao1.delete(connection, id);
}
private static void cleanupTnxLog(Connection connection, String id)
throws SQLException {
dao2.delete(connection, id);
}
}
【问题讨论】:
-
资源背后的想法是有一些自包含的东西(比如在之前()之前启动一个网络服务器并在之后()之后停止它)
-
@RC。我真的不想在测试类之间共享
Connection对象。但我不知道如何避免将相同的规则复制到其他所有课程中。该文档明确指出“ExternalResource 是规则(如 TemporaryFolder)的基类,它在测试之前设置外部资源(文件、套接字、服务器、数据库连接等),并保证在之后将其拆除”,所以我以为我可以将它用于数据库连接。 -
我不明白你为什么不能在这里使用规则。
标签: java unit-testing junit junit4 junit-rule