增加JdbcTemplate模拟的代码覆盖率 [英] increasing code coverage for JdbcTemplate mocking

查看:129
本文介绍了增加JdbcTemplate模拟的代码覆盖率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模拟 JdbcTemplate 用于单元测试用例,因为不想达到实际的数据库集成.

I am mocking JdbcTemplate for unit test cases, as don't want to hit actual database integration.

但这正在减少我的代码覆盖率(红色表示缺少覆盖率).

But it is decreasing my code coverage (Red indicates missing coverage).

下面是使用的代码段.使用用户定义的映射器也会发生相同的情况.

Below is the snippet used. Same case happens by using user defined mappers.

final List<String> resultList = new ArrayList<String>();
resultList.add("test1");
resultList.add("test2");
final JdbcTemplate template = Mockito.mock(JdbcTemplate.class);
Mockito.when(
    template.query(Mockito.anyString(), Mockito.any(Object[].class),
        Mockito.any(RowMapper.class))).thenReturn(resultList);
sampleDao.setJdbcTemplate(template);

关于dao类中的increasing code涵盖范围的任何想法.在我的情况下,所有方法都不适合用户定义的行映射器.

Any ideas for increasing code coverage in dao class. All methods doesn't suit for user defined row mappers in my case.

推荐答案

一种方法如下:

final List<String> resultList = new ArrayList<String>();
resultList.add("test1");
resultList.add("test2");

final JdbcTemplate template = mock(JdbcTemplate.class);

when(template.query(anyString(), any(Object[].class), any(RowMapper.class)))
    .thenAnswer(new Answer<List<String>>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            // Fetch the method arguments
            Object[] args = invocation.getArguments();

            // Fetch the row mapper instance from the arguments
            RowMapper<String> rm = (RowMapper<String>) args[2]; 

            // Create a mock result set and setup an expectation on it
            ResultSet rs = mock(ResultSet.class);
            String expected = "value returned by query";
            when(rs.getString(1)).thenReturn(expected);

            // Invoke the row mapper
            String actual = rm.mapRow(rs, 0);

            // Assert the result of the row mapper execution
            assertEquals(expected, actual);

            // Return your created list for the template#query call
            return resultList;
        }
    });

但是您可以看到,测试行映射器的代码很多:)

But as you can see, it's a lot of code to test the row mapper :)

就个人而言,我更喜欢进行集成测试,或者将行映射器移至其自己的类,并分别对其进行单元测试.

Personally, I would prefer going with an integration test OR moving the row mapper to a class of its own and unit testing it separately.

这篇关于增加JdbcTemplate模拟的代码覆盖率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆