3

This is my class

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

This is my test class,

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

I am getting the list with 0 size, but it should be one.

When i removed the Oject[]{} information from both source and test code , it works fine.

I am somewhere wrong in mocking Oject[] information, could someone please guide me.

jAvA
  • 557
  • 1
  • 8
  • 22
radha r
  • 115
  • 1
  • 3
  • 9

1 Answers1

0

you can use Matchers.anyObject() instead of any(Object[].class). ( import org.mockito.Matchers; )

jAvA
  • 557
  • 1
  • 8
  • 22
  • I tried like this and it worked , PowerMockito.when(jdbcTemplate.query(Matchers.anyString(), Matchers.any(RowMapper.class), Matchers.anyObject())).thenReturn(authenticationResourceTest.getDummyRoles()); The only difference is i don't have PowerMockito.whenNew. I think it is not required as it is already have @Mock annotation – jAvA Jan 13 '17 at 00:10