Jmockit/Spring mocked dependency still calls the Real dependency

spring jmockit

187 просмотра

1 ответ

41 Репутация автора

so I've been stuck on this problem all day.

I'm testing a class of type JdbcSupportDao in Spring 3.2. The problem is very self-explanatory if you just read the code, but I will briefly summarize:

I use the @Mocked annotation on a JdbcTemplate to mock querying the database. The problem is, after writing the Expectations block, the actual JdbcTemplate method is still being called, with JMockit apparently not entering in to the equation at all.

The following unit test fails:

@ContextConfiguration(locations={"classpath:studentAggregateReport-servlet.xml", "classpath:applicationContext-hibernate.xml"})
public class JdbcSSODaoTest   extends AbstractTransactionalJUnit4SpringContextTests {

    JdbcTemplate jdbcTemplate;

    List<String> unameList;

    SSODao ssoDao;

    String DUMMY_ALCID = "yattayattayatta";

    public void constructDao() {
        this.ssoDao = new JdbcSSODao();
        ((JdbcSSODao) ssoDao).setJdbcTemplate(jdbcTemplate);

    public void testGetUnameFromAlcId() {
        unameList = new ArrayList<String>() {{
        //((JdbcSSODao) ssoDao).setJdbcTemplate(jdbcTemplate);
        new Expectations() {{
            jdbcTemplate.query(anyString, (ResultSetExtractor<String>)any); result = unameList;

        String uname = ssoDao.getUnameFromAlcId(DUMMY_ALCID);



and here is the code for the class being tested:

public class JdbcSSODao extends JdbcDaoSupport implements SSODao {

    public String getUnameFromAlcId(String alcid) {
        String sql = SSOSqlUtil.createGetUnameByAlcIdSql(alcid);
        List<String> resultLst = getJdbcTemplate().query(sql, new RowMapper<String>() {
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getString(1);
        if(resultLst.isEmpty()) return null;
        return resultLst.get(0);


Please help :(

Автор: ramziabbyad Источник Размещён: 05.04.2017 09:04

Ответы (1)

0 плюса

41 Репутация автора

Sweet mother of God..

Apparently, you have to cast parameters of mocked methods to the exact type used in the call. This fixed it for me:

    new Expectations() {{
        jdbcTemplate.query(anyString, (RowMapper<String>)any); result = unameList;
Автор: ramziabbyad Размещён: 05.04.2017 09:24
Вопросы из категории :