Spring jdbcTemplate Junit

天涯浪子 提交于 2020-01-05 04:07:11

问题


I have one application with DAO as follows. I want to junit this class. My Class looks like this.

    public class DaoImpl implements Dao{

    @Override
    public User getUserInfo(String userid) {
        return getTemplate().queryForObject(QUERY, new Object[] { userid },
                new BeanPropertyRowMapper<User>(User.class));
     }

   }

My junit class looks like this

@RunWith(SpringJUnit4ClassRunner.class)
public class DaoImplTests{

    @Autowired
    private Dao dao;

    @Mock
    JdbcTemplate jdbcTemplate;

    @Test
    public void testUsingMockito() {
        try {
            User mockedUserInfo = new User();
            //setters
            mockedUserInfo.setXXX;
            mockedUserInfo.setYYY;

            Mockito.when(((JdbcDaoSupport)dao.getTemplate())).thenReturn(jdbcTemplate);
            Mockito.when(jdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(Object[].class),
                    Mockito.any(RowMapper.class))).thenReturn(mockedUserInfo);
            User userInfo = dao.getUserInfo("");
            Assert.assertNotNull(userInfo);
            Assert.assertEquals(mockedUserInfo.getXXX(), userInfo.getXXX());
            //few more assertions
        } catch (Exception e) {
            Assert.fail(" : " + e.getMessage());
        }
    }

}

When I execute this test case I get following exception from mockito.

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
2. inside when() you don't call method on mock but on some other object.
3. the parent of the mocked class is not public.
   It is a limitation of the mock engine.

My Queries :

  1. How to junit my class
  2. This exception is coming because getJdbcTemplate is final JdbcDaoSupport class. Is there any alternative for this approach?

I wrote my junit using post Spring jdbcTemplate unit testing

But, looks like it doesn't work.


回答1:


You problem is with this line:

Mockito.when(((JdbcDaoSupport)dao.getTemplate())).thenReturn(jdbcTemplate);

You have dao annotated with @Autowired so it is not a mocked object. What you want to probably do is use SpringTestReflectionUtils to set your jdbcTemplate in the dao to your mocked object.



来源:https://stackoverflow.com/questions/38374823/spring-jdbctemplate-junit

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