Last week I published an article, An Intro into Test Driven Development with Junit4, which got somewhat mixed reviews. One particular commenter on reddit suggested I didn't understand that unit tests shouldn't talk to its data source. I decided to do some investigating into his claims, you can check out my findings here. I was however intrigued none the less and started looking for a tool that would allow me to easily mock a JDBC connection. I found Mockrunner to be the easiest to use of the ones I have found. Below is a brief tutorial on how to use Mockrunner. (Keep in mind that I am still fairly new to using Mockrunner)
In the class I am testing I am explicitly calling the columns I am retrieving by name. So I need to add these column names to my mock ResultSet.
result.addColumn("Date"); result.addColumn("High"); result.addColumn("Low"); result.addColumn("Condition"); result.addColumn("ID");
Obviously I also retrieve data from a result set so I must also insert data into the mock ResultSet. There are several ways to do this, but the easiest I found was using a list. You must add elements to the list in the same order as you added columns to the ResultSet.
List<Object> rowItems = new ArrayList<Object>(); rowItems.add(new Date(0)); rowItems.add(72); rowItems.add(56); rowItems.add("Cloudy"); rowItems.add(1);
In my actual test case I can verify that I am actually gathering the contents of the result set correctly and that the correct SQL statement was run.
prepareRS(); ForecastDAO dao = new ForecastDaoImpl(getConnection()); List<Forecast> forecasts = dao.getAllForecasts(); assertTrue(!forecasts.isEmpty()); verifySQLStatementExecuted("SELECT * FROM forecast"); assertEquals(73, forecasts.get(1).getHigh());
This is but scratching the surface of MockRunner's potential and using mocks at large. I hope this brief tutorial was helpful in getting you started using MockRunner. You can checkout the entire test class here and the class that I am testing here. If you want to get an entire working version of the project be sure to read the technical guide. Let me know if you have any questions or want to add your own comments.