As a homework exercise (I'm a beginner) I had to write a Java program which accesses a database (PostgreSQL). The program can, e.g., insert new users, increment some fields etc. and I have methods such as: addUser(User t), deleteUser(User t) and so on.
I also have written test methods using junit5. For the tests I use a 'test' database, separate from the 'work' one. The coordinates to open the two databases (database name, password etc.) are stored in two files called config.properties and config.test.properties, which are selected at runtime.
What I have in place now is something along these lines, using a boolean flag variable:
public class UserDao {
public boolean isTestMode = false;
public Connection getConnection() {
if (this.isTestMode) {
input = cl.getResourceAsStream("config.test.properties");
} else {
input = cl.getResourceAsStream("config.properties");
}
...
}
}
In my test methods I then set the flag like this:
void testAddUser() {
UserDao dao = new UserDao();
dao.isTestMode = true;
...
}
In regular, non-test method I don't set isTestMode, which therefore stays to its default (false) value and config.properties is used. My approach works, but my instructor told me it is bad practice to do things like this and I should change it, for example (he suggested) doing a dependency injection. I'm not too sure how to proceed. I could make configFilename a class variable and add to the class UserDao a new constructor which accepts a filename, like this:
public class UserDao {
private String configFilename = "config.properties";
public UserDao() {
}
public UserDao(String filename) {
this();
this.configFilename = filename;
}
public Connection getConnection() {
input = cl.getResourceAsStream(this.configFilename);
...
}
}
Then in the test methods I use the new construtor UserDao("config.test.properties")
A (in my view a better) variant is to introduce a constructor which accepts a boolean isTestMode and sets configFilename accordingly (I don't need nor want the flexibility of specifying any filename in the constructor). But essentially this is the same as my original approach, which I was told to change. Also, there no dependency injection there... what is it best practice in such cases? Any suggestion would be welcome!