使用powermock时调用真实方法

时间:2019-02-18 05:50:04

标签: spring-boot mockito junit4 powermockito

@RunWith(PowerMockRunner.class) 
@PrepareForTest(FCMServiceImpl.class) 
public class PowerMockTest {    

    FCMServiceImpl fcmService;

    FCMService fcmServiceInt;


    @Mock
    private RestTemplate restTemplate;
    @Mock
    private GprsDeviceRepository fcmDeviceRepository;
    @Mock
    private FcmMessagesRepository fcmMessagesRepository;
    @Mock
    private FcmQueryImpl fcmQueryImpl;
    @Mock
    private BatchFcmRepository batchFcmRepository;
    @Mock
    private BatchFcmInsertAsync batchFcmInsertAsync;

    @Before
    public void setUp() {
        fcmService = PowerMockito.spy(new FCMServiceImpl(restTemplate,
                fcmDeviceRepository,
                fcmMessagesRepository,
                fcmQueryImpl,
                batchFcmRepository,
                batchFcmInsertAsync));
        fcmServiceInt = Mockito.spy(FCMService.class);
    }

    @Test
    public void Testify() throws Exception {
        HashMap<String, String> a = new HashMap<>();
        FCMServiceImpl g = mock(FCMServiceImpl.class);
        a.put("error_message", "54321");
        AdminFcmResource fcmResource = AdminFcmResource.builder().adminId(123L).build();
        Mockito.doReturn(fcmResource).when(fcmService).addBulkFcmLog(new BulkFcmDataResource());
        PowerMockito.doReturn(a)
                .when(fcmService, "exchangeForTopic", anyString(), anyObject());
        fcmService.sendFcmByTopic(new BulkFcmDataResource());
    } }

我正在使用powermock模拟一些私有和公共方法

 @Override
public void sendFcmByTopic(BulkFcmDataResource adminFcmResource) throws RestServiceException {
    AdminFcmResource adminBulkFcmResource = addBulkFcmLog(adminFcmResource); // an overriden public method
    pushFCMToTopics(adminBulkFcmResource);// private method, calls the exchange method which i stubbed
}

FcmService是一个接口,而FcmServiceImpl是一个实现。从测试中调用sendFcmByTopic方法时,将执行实际方法addBulkFcmResource。我尝试创建FcmService接口的Mockito.spy,然后执行sendFcmByTopic方法,但是当使用mockito.spy时,interface.sendFcmByTopic不会被调用。

根据我的理解,如果未存根,是否不应该调用该方法?

为什么私有方法存根在powermockito中起作用但在公共方法中不起作用?

0 个答案:

没有答案