我在努力了解使用ExternalResource
的好处。 documentation和其他帖子(How Junit @Rule works?)都被暗示能够在一个类中的测试之间共享代码和/或在测试类之间共享代码。如何在两个测试类之间共享ExternalResource?
我想在功能/集成测试中使用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);
}
}
资源背后的想法是有一些独立的东西(比如在()之前启动一个web服务器并在()之后停止它)@RC – 2014-01-10 21:27:33
。我真的不想在测试类之间共享'Connection'对象。但我不明白我能如何避免将同一个规则复制到其他任何类中。该文件特别声明“ExternalResource是一个规则的基类(如TemporaryFolder),它在测试之前设置了一个外部资源(文件,套接字,服务器,数据库连接等),并保证在事后才将其拆除”我认为我可以将它用于数据库连接。 – user1766760
我不明白你为什么不能在这里使用规则。 – 2014-01-10 21:38:55