当我们传递参数(RowMapper)时,如何模拟模拟Spring JDBC?

3

这是我的班级

@Repository
public class JdbcRolesDao implements RolesDao{
private JdbcTemplate jdbcTemplate;

private static final String GET_USER_ROLES_QUERY = "select ROLE_CD from USER_ROLES where USER_ID = ? AND USER_DRCTRY = ?";

@Autowired
public JdbcRolesDao(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
}

public List<String> getRolesByUser(String userId, String directoryId){
    List<String> roles = jdbcTemplate.query(
            GET_USER_ROLES_QUERY , new RoleMapper(), new Object[]{userId, directoryId});
    return roles;
}}

这是我的测试类,
@RunWith(PowerMockRunner.class)
@PrepareForTest({JdbcRolesDao.class})
public class JdbcRolesDaoTest {

@Mock
private DataSource datasource;

@Mock
private JdbcTemplate jdbcTemplate;

private JdbcRolesDao jdbcRolesDao;

private static AuthenticationResourceTest2 authenticationResourceTest;

private static final String GET_USER_ROLES_QUERY = "select ROLE_CD from USER_ROLES where USER_ID = ? AND USER_DRCTRY = ?";

@BeforeClass
public static void init(){
   authenticationResourceTest = new AuthenticationResourceTest2();
}

@Before
public void initMocks() throws Exception {
   MockitoAnnotations.initMocks(this);
   PowerMockito.whenNew(JdbcTemplate.class).withAnyArguments().thenReturn(jdbcTemplate);
   jdbcRolesDao = new JdbcRolesDao(datasource);
}

@Test
public void getRolesByUserTest(){
    PowerMockito.when(jdbcTemplate.query(anyString(), any(RowMapper.class),any(Object[].class))).thenReturn(authenticationResourceTest.getDummyRoles());
    List<String> configList = jdbcRolesDao.getRolesByUser("UserId", "DirectoryId");
    if(configList != null)
        System.out.println("not null "+configList.size());
    //assertThat(configList, Matchers.hasSize(1));
}}

我的列表大小为0,但应该是1。

当我从源代码和测试代码中删除了Oject[]{}信息后,它就正常工作了。

在模拟Oject[]信息时,我做错了什么地方,请有经验的人指导。

1个回答

0

你可以使用Matchers.anyObject()代替any(Object[].class)。(导入org.mockito.Matchers;)


我尝试了这样做,它起作用了,PowerMockito.when(jdbcTemplate.query(Matchers.anyString(), Matchers.any(RowMapper.class), Matchers.anyObject())).thenReturn(authenticationResourceTest.getDummyRoles()); 唯一的区别是我没有 PowerMockito.whenNew。我认为它不需要,因为它已经有 @Mock 注释。 - jAvA

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接