简体   繁体   中英

Should I persist JDBC connection or not?

For my integration tests I have build common validation class which has methods like

public void countcheck(table1, table 2){ // makes a JDBC connection and run the query to check counts and then closes the connection };

public void nullcheck(Table, ColumnName) {// makes a JDBC connection and the run query to make sure there are no Nulls and then closes the connection );

and so on. I distribute these common validation methods as Jars for integration testers. My dilemma is whether I should open and close connection for each method , I don't want testers to worry about opening and closing connections and just worry about calling validation methods. I am looking for alternative design or this is something good enough. My worry is if there in a test suite there are 10 tests then there would be 10 connections going and closing which perhaps is not a good sign? I want testers to worry about makig and closing connections. Its a Junit based test framework and DB is Oracle.

You should not "bake in" the decision on handling DB connections into your code. Instead, you should defer this decision to people deploying your framework.

If they decide to reuse connections, they could configure connection pool for that; if they decide to open and close connections every time, they could configure the framework without connection pooling.

Your task is reduced to providing the enabling technology to them.

I typically pass a DataSource into such Objects (constructors) and get the connection on each business Method. In standalone mode this might mean it is not using a proper pool, but when you onlyexecute a handfull of statements thats no problm.

In production you can then pass in a real pool. The advantage of keeping a data source around as opposed to a Connection is, that this scenario has better self-healing capabilities and reducesthe number of active connections. (It might be not so important in test scenarios, but whynot have generally useable validators).

Validator(DataSource ds) {
    this.ds = ds;
}
validate(String val, ...) {
    try (Connection c = ds.getConnection()) {
        ...
    }
}

Most drivers have a native DataSource, but you can also have a genericone which implements getConnection() to return DriverManager.getConnection(url); . It is also a small interface easily mockable.

If your tests get bigger, you use a simple pooling datasource like the one from Apache Commons DBCP DriverAdapterCPDS .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM