簡體   English   中英

如何在兩個測試類之間共享ExternalResource?

[英]How to share an ExternalResource between two test classes?

我正在努力了解使用ExternalResource的好處。 文檔和其他帖子( Junit @Rule如何工作? )都提到能夠在類中的測試之間共享代碼和/或在測試類之間共享代碼。

我試圖在功能/集成測試中使用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);
    }
}

我會做那樣的事情:

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...
    }

    // ...
}

[未經測試]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM