Context/Scenario:
I am using JUnit along with Apache Log4J to learn TDD and Logging services best practices. I have a GenericTaskInterpreter
class which has a method connectToMySQL
which will attempt to connect to a MySQL database and return an object of type java.sql.Connection
.
class GenericTaskInterpreter {
/**
* This method will attempt to connect to a MySQL database
* and return an object of type java.sql.Connection
*/
public Connection connectToMySQL() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/TestDatabase", "root",
"password");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return connection;
}
}
And I have a class GenericTaskInterpreterTests
where I have written the test cases for this method(and other methods).
public class GenericTaskInterpreterTests extends TestCase {
private static final GenericTaskInterpreter genericTaskInterpreter = new GenericTaskInterpreter();
private static final Logger logger = LogManager.getLogger(GenericTaskInterpreterTests.class);
private static boolean setUpIsDone = false;
private static boolean tearDownIsDone = false;
private static FileAppender fileAppender;
@Rule
public TestRule watchman = new TestWatcher() {
private String watchedLog;
// Overridden methods apply, succeeded, skipped, starting and finished....
};
protected void setUp() throws Exception {
if (setUpIsDone) {
return;
}
// Do the setup.
fileAppender = new FileAppender();
fileAppender.setName("FileLogger");
fileAppender.setFile("/path/to/log4j-application.log");
fileAppender.setLayout(new PatternLayout("%d %-5p [%c{1}.%M] %m%n"));
fileAppender.setThreshold(Level.DEBUG);
fileAppender.setAppend(true);
fileAppender.activateOptions();
LogManager.getRootLogger().addAppender(fileAppender);
setUpIsDone = true;
//logger.info("####### All configurations complete... #######");
logger.info("####### Starting test cases... #######");
}
protected void tearDown() throws Exception {
if (tearDownIsDone) {
return;
}
// Do the teardown.
//fileAppender.close();
LogManager.getRootLogger().removeAppender(fileAppender);
tearDownIsDone = true;
}
public void testconnectToMySQLIfConnectionObjectIsNotNull() {
assertNotNull(genericTaskInterpreter.connectToMySQL());
}
}
Questions:
- How to use TestWatcher for logging assertion failures in this test case scenario?
- Is there a better alternative than using TestWatcher?