有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在两个测试类之间共享外部资源?

我正在努力理解使用ExternalResource的好处。documentation和其他帖子(How Junit @Rule works?)都暗示了能够在类内的测试之间共享代码和/或在测试类之间共享代码

我试图在功能/集成测试中使用ExternalResource作为DB连接,但我不知道如何在类之间共享该连接。事实上,在这种情况下,我并不认为@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);
    }
}

共 (1) 个答案

  1. # 1 楼答案

    我会这样做:

    public class DbConnectionRessource extends ExternalRessource {
    
        private Connection connection;
    
        @Override
        protected void before() throws SQLException {
            connection = DbUtil.openConnection();
        }
    
        @Override
        protected void after() {
            DbUtil.closeConnection(connection);
        }
    
        public Connection getConnection() {
            return connection;
        }
    }
    

    然后在测试中使用它,如下所示:

    public class SomeIntegrationTest {
        @Rule
        public DbConnectionRessource dbConnectionResource = new DbConnectionRessource();
    
        // ...
    
        @Test
        public void test01() {
            cleanupData(dbConnectionResource.getConnection(), id);
            // do stuff...
        }
    
        // ...
    }
    

    [未经测试]