0

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);
    }
}
Mike Kng
  • 255
  • 2
  • 11

1 Answers1

0

Mocking in unit tests helps you test the part of your code that would otherwise be using a resource. Using it to test a class where it's only purpose is to establish connection to a resource makes no sense.

This functionality will be tested during an integration testing. See more on integration and unit testing here

Péter Veres
  • 955
  • 1
  • 10
  • 25