mercredi 23 janvier 2019

Testing jdbc connection class

I try to learn to test my projects correctly and continuously. Unfortunately there are a few things I don‘t understand since there are a lot of different opinions on the topic. What I don’t get is how to decide which classes are „worth“ testing them. As an example I took the example JDBC connection class from oracle:

public Connection getConnection() throws SQLException {
    Connection conn = null;
    Properties connectionProps = new Properties();
    connectionProps.put("user", this.userName);
    connectionProps.put("password", this.password);
    if (this.dbms.equals("mysql")) {
        conn = DriverManager.getConnection(
                   "jdbc:" + this.dbms + "://" +
                   this.serverName +
                   ":" + this.portNumber + "/",
                   connectionProps);
    } else if (this.dbms.equals("derby")) {
        conn = DriverManager.getConnection(
                   "jdbc:" + this.dbms + ":" +
                   this.dbName +
                   ";create=true",
                   connectionProps);
    }
    System.out.println("Connected to database");
    return conn;
}
 

I know I can mock objects to be able to look at the class more isolated. Is it even useful to test a class like this, or can I benefit from doing something like this, to see if a connection could theoretically be made?

public class TestClass {

    @Mock
    private Connection conn;

    @Mock
    private Database database;

    @BeforeEach
    public void setUp() throws Exception {
        assertNotNull(database);
        when(database.getConnection()).thenReturn(conn);
    }
}

Aucun commentaire:

Enregistrer un commentaire