Better test coverage and reuse with interfaces and mocks
From Coder's Log
Separating our code into methods is nothing new, and isn't really what OOP is all about, but its necessary to understand when to use methods and when to use classes and interfaces.
We will start where we left of in the The basics, how to test simple programs without using interfaces. If you haven't done so already it is also a good idea to look at What are mock objects and Using EasyMock to create mock objects on the fly.
public class FooQuoteToCsvConverter {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/foo", "user", "foo");
Statement s = conn.createStatement();
s.executeQuery("SELECT symbol, company_name FROM stock_symbols");
ResultSet rs = s.getResultSet();
System.out.println(createCsvLine("Symbol", "Company_Name"));
while (rs.next()) {
String symbol = rs.getString("symbol");
String companyName = rs.getString("company_name");
System.out.println(createCsvLine(symbol, companyName));
}
rs.close();
s.close();
conn.close();
}
public static String createCsvLine(String symbol, String companyName) {
String quotedCompany = companyName.contains(",") ? "'" + companyName + "'" : companyName;
return symbol + "," + quotedCompany;
}
}
And our test case
public class FooQuoteToCsvConverterTests extends TestCase {
public void testSimple() {
assertEquals("S,COMPANY", FooQuoteToCsvConverter.createCsvLine("S", "COMPANY"));
}
public void testComplex() {
assertEquals("S,'COMPANY , WITH A COMMA'", FooQuoteToCsvConverter.createCsvLine("S", "COMPANY , WITH A COMMA"));
}
}
We managed to isolate and test the true function of the program, but we left out the process of how the program works as a whole, and we left out exception handling and validating that all of the statements/resultsets/connections have been properly closed. Our tests also do not make sure that a header is printed with the csv. Reusing this code is very unlikely.
Our process is as follows:
- Connect to the database
- Read data from database
- Write csv to output stream
