java - Spring jdbcTemplate Junit

标签 java spring junit spring-jdbc jdbctemplate

我有一个使用 DAO 的应用程序,如下所示。我想混这门课。我的类(class)看起来像这样。

    public class DaoImpl implements Dao{

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

   }

我的 junit 类看起来像这样

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

}

当我执行这个测试用例时,我从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.

我的查询:

  1. 如何对我的类(class)进行分组
  2. 出现此异常是因为 getJdbcTemplate 是最终的 JdbcDaoSupport 类。这种方法还有其他选择吗?

我使用帖子Spring jdbcTemplate unit testing编写了我的junit

但是,看起来它不起作用。

最佳答案

你的问题出在这一行:

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

您使用 @Autowired 注解了 dao,因此它不是模拟对象。您可能想要做的是使用 SpringTestReflectionUtils 将 dao 中的 jdbcTemplate 设置为您的模拟对象。

关于java - Spring jdbcTemplate Junit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38374823/

相关文章:

java - com.sun.servicetag.*。我的 eclipse luna IDE 中丢失了

java - 从 Tomcat : No buffer space available 发送 SMTP 消息时出错

java - Hibernate/Spring框架: path of the database in a configuration file

java - Spring AoP 在切入点中引用以某个字符串结尾的任何包中所有类的所有方法

java - 将 PowerMockRunner 与 Junit 测试套件结合使用

java - OutOfMemoryException - 使用 Glide 的最佳方式

java - 依赖注入(inject)如何在 Cucumber 中工作?

spring - 使用 Spring MVC Test 对多部分 POST 请求进行单元测试

java - 如何使用mockito模拟junit中的连续调用方法?

java - 强化高 : Access specifier manipulation on reflection that is used to invoke a private constructor