JdbcTemplate

时间:2019-03-27 11:08:23

标签: mockito 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));
        }


    }

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

通过如下更改将其修复:

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