Spring DA helps in writing DAOs. When using iBATIS as the persistence framework, and extending SqlMapClientDaoSupport, a SqlMapClient mock should be set for the DAO, but I can't do it. SqlMapClientTemplate is not an interface and EasyMock cannot creates a mock for it.
DAO and unit tests do not get along well ! That does not make sense to mock anything in a component that does not hold any business logic and is focused on database access. You should try instead to write an integration test. Take a look at the spring reference documentation, chapter 8.3 : http://static.springframework.org/spring/docs/2.5.x/reference/testing.html
This exact reason is why I don't extend from SqlMapClientDaoSupport
. Instead, I inject a dependency to the SqlMapClientTemplate
(typed as the interface SqlMapClientOperations
). Here's a Spring 2.5 example:
@Component
public class MyDaoImpl implements MyDao {
@Autowired
public SqlMapClientOperations template;
public void myDaoMethod(BigInteger id) {
int rowcount = template.update("ibatisOperationName", id);
}
}
As @Banengusk suggested - this can be achieved with Mockito. However, it is important to establish that your DAO will be using a Spring SqlMapClientTemplate
that wraps your mock SqlMapClient
. Infact, SqlMapClientTemplate
delegates invocations to the SqlMapSession
in the IBatis layer.
Therefore some additional mock setup is required:
mockSqlMapSession = mock(SqlMapSession.class);
mockDataSource = mock(DataSource.class);
mockSqlMapClient = mock(SqlMapClient.class);
when(mockSqlMapClient.openSession()).thenReturn(mockSqlMapSession);
when(mockSqlMapClient.getDataSource()).thenReturn(mockDataSource);
dao = new MyDao();
dao.setSqlMapClient(mockSqlMapClient);
We can then verify behaviour like so:
Entity entity = new EntityImpl(4, "someField");
dao.save(entity);
ArgumentCaptor<Map> params = ArgumentCaptor.forClass(Map.class);
verify(mockSqlMapSession).insert(eq("insertEntity"), params.capture());
assertEquals(3, params.getValue().size());
assertEquals(Integer.valueOf(4), params.getValue().get("id"));
assertEquals("someField", params.getValue().get("name"));
assertNull(params.getValue().get("message"));