gpt4 book ai didi

java - Spring jdbcTemplate Junit

转载 作者:太空宇宙 更新时间:2023-11-04 12:26:07 30 4
gpt4 key购买 nike

我有一个使用 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com