How to unit test a DAO that is extending SqlMapClientDaoSupport

心不动则不痛 提交于 2019-12-07 05:39:38

问题


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.


回答1:


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




回答2:


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);
    }
}



回答3:


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"));



回答4:


Try Mockito. It lets mock classes, not only interfaces.



来源:https://stackoverflow.com/questions/110592/how-to-unit-test-a-dao-that-is-extending-sqlmapclientdaosupport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!