在 JdbcTemplate 中模拟重载方法查询对象



如何使用mockito模拟下面的代码?

@Override
@Nullable
public <T> T queryForObject(String sql, Object[] args, int[] argTypes, Class<T> requiredType)
        throws DataAccessException {
    return queryForObject(sql, args, argTypes, getSingleColumnRowMapper(requiredType));
}

我在下面尝试过:

  @Test
    public void testGetCount(){
        Mockito.when(jdbcTemplate.queryForObject(ArgumentMatchers.anyString(),Mockito.refEq(Object[].class),
                Mockito.refEq(Integer[].class), Mockito.eq(Long.class)))
                .thenAnswer((Answer<Long>) invocation -> 2l);
        User user = new User(userDetails);
        Assert.assertEquals(2,dao.getCount(user));
    }

请注意,我尝试过使用 Mockito.eq 而不是 Mockito.refEq ,但以相同的结果结束。

但它总是调用以下方法:

@Override
    public <T> T queryForObject(String sql, Class<T> requiredType, @Nullable Object... args) throws DataAccessException {
        return queryForObject(sql, args, getSingleColumnRowMapper(requiredType));
    }

全班在这里:

    public class UserDetailsAggregationDaoTest {
        private final String userDetails = "10015-MTBD";
        @InjectMocks
        private UserDao dao = new UserDaoImpl();
        @Mock
        private JdbcTemplate jdbcTemplate;


   @Test
        public void testGetCount(){
            //Using Mockito.refEq
            Mockito.when(jdbcTemplate.queryForObject(ArgumentMatchers.anyString(),Mockito.refEq(Object[].class),
                    Mockito.refEq(Integer[].class), Mockito.eq(Long.class)))
                    .thenAnswer((Answer<Long>) invocation -> 2l);
            User user = new User(userDetails);
            Assert.assertEquals(2,dao.getCount(user));
        }

    }

任何帮助将不胜感激

通过像下面这样更改它来修复它:

Mockito.when(jdbcTemplate.queryForObject(ArgumentMatchers.anyString(),Mockito.any(Object[].class),Mockito.any(int[].class), Mockito.eq(Long.class)))
            .thenReturn(2l);

相关内容

  • 没有找到相关文章

最新更新