如何使用PowerMockito模拟super.method

时间:2017-04-12 15:07:33

标签: java junit powermock powermockito

如何使用power mock模拟超类方法。在CardRepo中我使用超类方法来获取jdbcTemplate但是使用power mock我无法在CardRepo类中模拟super.method。如何使用power mock来模拟super.getJdbcTemplate()。

public abstract class AbstractRepository {
    @Autowire
    private static JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
}
Class CardRepo extends AbstractRepository{
    @Override
    public List<Card> getCardList(CommonInputBean inputBean) {
        List<Card> data=Collections.emptyList();
        data = super.getJdbcTemplate().query(query.toString(), new BeanRowMapper<Card>(Card.class)); // how to mock
        return data;
    }
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({ CardRepo.class})
class CardTest{
    @Spy
    private CardRepo cardRepository = new CardRepo();
    @Test
    public void getCardList() {         
            Method method = PowerMockito.method(AbstractRepository.class, "getJdbcTemplate");
            PowerMockito.suppress(method);
            Method methodFoo = PowerMockito.method(AbstractRepository.class, "getJdbcTemplate");
            PowerMockito.replace(methodFoo).with(new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    return jdbcTemplate;
                }
            });
            PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(AbstractRepository.class));
            CardRepositoryImpl child = PowerMockito.spy(new CardRepositoryImpl());
            child.getJdbcTemplate();
            PowerMockito.when(child.getJdbcTemplate()).thenReturn(jdbcTemplate);
            List<Card> list = this.cardRepository.getCardList(inputBean);
    }
}

0 个答案:

没有答案