2014-01-10 52 views
0

我在努力了解使用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); 
    } 
} 
+0

资源背后的想法是有一些独立的东西(比如在()之前启动一个web服务器并在()之后停止它)@RC – 2014-01-10 21:27:33

+0

。我真的不想在测试类之间共享'Connection'对象。但我不明白我能如何避免将同一个规则复制到其他任何类中。该文件特别声明“ExternalResource是一个规则的基类(如TemporaryFolder),它在测试之前设置了一个外部资源(文件,套接字,服务器,数据库连接等),并保证在事后才将其拆除”我认为我可以将它用于数据库连接。 – user1766760

+0

我不明白你为什么不能在这里使用规则。 – 2014-01-10 21:38:55

回答

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

    // ... 
} 

[未测试]

+0

我试过在测试中创建的'ExternalResource'规则之前这样做(现在我看到当然不会工作,因为我没有扩展... pfft) – user1766760