简体   繁体   English

单元测试DAO

[英]Unit test a DAO

I've been trying to do a unit test of my DAO but I haven't find out the way to do it yet and I'm feeling a little desperate. 我一直试图对我的DAO进行单元测试,但我还没有找到方法去做,我感觉有点绝望。 I have a tiny DAO that looks like this: 我有一个看起来像这样的小DAO:

public interface ElectionsDao {
    List<String> getDates();
}

I'm using Spring framework to do DI using SimpleJdbcTemplate . 我正在使用Spring框架使用SimpleJdbcTemplate进行DI。 My implementation looks like this: 我的实现看起来像这样:

public class ElectionsDaoImpl extends SimpleJdbcDaoSupport implements ElectionsDao {
    public List<String> getDates() {
        List<String> dates = new ArrayList<String>();
        try {
            dates = getSimpleJdbcTemplate().query("SELECT electiondate FROM electiondate", new StringRowMapper());
        } catch (DataAccessException ex){
            throw new RuntimeException(ex);
        }
        return dates;
    }

    protected static final class StringRowMapper implements ParameterizedRowMapper<String> {
        public String mapRow(ResultSet rs, int line) throws SQLException {
            String string = new String(rs.getString("electiondate"));
            return string;
        }
    }
}

What I want to do is just a unit test of getDates() using EasyMock but I haven't found the way to do it. 我想要做的只是使用EasyMock对getDates()进行单元测试,但我还没有找到方法。 I'm so confused. 我很困惑。 Can anybody help me please? 有人能帮帮我吗?

It looks as though getSimpleJdbcTemplate is the biggest problem for unit testing. 看起来getSimpleJdbcTemplate似乎是单元测试的最大问题。 One way you could test is to extend the class under test and override the getSimpleJdbcTemplate method eg 您可以测试的一种方法是扩展测试中的类并覆盖getSimpleJdbcTemplate方法,例如

public class ElectionDaoTest {

    /** Class under test */
    private ElectionsDaoImpl dao;

    @Before
    public void setUp() {
        dao = new ElectionsDaoImpl(){
            SimpleJdbcTemplate getSimpleJdbcTemplate(){
                // Return easy mock version here.
            }
        };
    }

    @Test
    // Do tests
}

There may be an easier way with EasyMock, but I'm not that familiar with it. EasyMock可能有一种更简单的方法,但我对它并不熟悉。

Thank you for your comments. 谢谢您的意见。 I decided to do the test using Spring. 我决定使用Spring进行测试。 My test code ended like this: 我的测试代码结束如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:beans.xml")
public class DBConectionTest{

    @Resource
    private ElectionsDao electionsDao;

    @Test
    public void testGetDates(){
        List<String> dates = electionsDao.getDates();
        assertNotNull(dates);
    }
}

I'm using the same xml file that I use when running my project. 我正在使用运行项目时使用的相同xml文件。 Hope it helps someone. 希望它可以帮助某人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM