Friday 21 June 2013

JDBC DAO Unit Test using Mockito

For some, it's hard to think of unit testing a DAO without actually interacting with a database. This example illustrates a basic unit test for a dao class, that uses a Spring NamedParameterJdbcTemplate, without the need to actully query the underlying database:

package com.blah.test.dao;

import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.refEq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.test.util.ReflectionTestUtils;

public class MockJdbcLookUpDAOTest {

private JdbcLookUpDAODAO dao;

@Mock
private NamedParameterJdbcTemplate namedTemplate;

private static final String SAMPLE_SQL = "SELECT * " +
"FROM SOME_TABLE " +
"WHERE ID = :id";

@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
dao = new JdbcFssCodeLookUpDAO();

//Spring utility class for use in unit and integration testing scenarios.
//Allows mocks to be used where no setters are accessible
ReflectionTestUtils.setField(dao, "namedTemplate", namedTemplate);
}

@Test
public void testGetFssCodeUpByPostcode(){

MapSqlParameterSource param = new MapSqlParameterSource();
param.addValue("id", "1");

//Mock the named template call to return a known String, 
//without the need for any db look up, as this would be an integration test
given(namedTemplate.queryForObject(eq(SAMPLE_SQL), refEq(param), eq(String.class))).willReturn("K");

//call the dao method, but trigger the above mock method call
String fssCode = dao.doLookUp(((String) param.getValue("id"));

//check the named template method was called once, with the expected query string and parameter values
verify(namedTemplate, times(1)).queryForObject(eq(FSS_CODE_BY_POSTCODE_SQL), refEq(param), eq(String.class));

//Check the dao method returns the expected value
assertEquals(fssCode, "K");

}


}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.