Reputation: 1897
I want simple test for JDBC connection, I don't use framework, only JDBC and JUnit. Can I perform this test with JUnit? I have no idea how to even test loading driver, please give me some example of connection test.
Connection client:
package newpackage.db;
import java.sql.Connection;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SqlConnection {
private Connection con;
private String name;
private String url;
private String password;
private String driver;
public SqlConnection() {
this.name = "root";
this.password = "12345";
this.url = "";
this.driver = "com.mysql.jdbc.Driver";
}
public Connection getConnection() {
try {
Class.forName(driver);
} catch (ClassNotFoundException ex) {
Logger.getLogger(SqlConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
Test case:
public void testDriverManager() {
SqlConnection conClient = new SqlConnection();
assertEquals(conClient.getConnection(),...);
or
assertTrue(conClient.getConnection(),...);
}
Upvotes: 5
Views: 28140
Reputation: 2625
Basically, you can follow this guide for the drivermanager in order to establish a connection.
http://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html
The best test for a connection is reading some basic stuff from your database. E.g. select 1 from dual
Be aware that this test requires a running database! Keep the amount of these integrative tests low, as they do not scale well and require a certain environment given. It makes continuous integration on e.g. Hudson kind of more difficult, as you will have to install a database on all continuous integration server nodes and keep it running.
Upvotes: 3