【问题标题】:How to Mock mock Spring JDBC when we pass with parameter (RowMapper)当我们传递参数时如何模拟模拟 Spring JDBC (RowMapper)
【发布时间】:2017-01-11 19:50:33
【问题描述】:

这是我的课

@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,但它应该是一个。

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

我在模拟 Oject[] 信息时出错了, 有人可以指导我吗?

【问题讨论】:

    标签: spring junit mockito powermockito


    【解决方案1】:

    您可以使用 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 注释
    猜你喜欢
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    相关资源
    最近更新 更多