使用Powermockito在junit中模拟私有方法

时间:2015-07-15 07:09:06

标签: java powermockito

我需要模拟以下方法调用carBookBuilder.setTrip(protoConverter.convertTrip(carBookRequest, location)),但是当carBookBuilder.setTrip(protoConverter.convertTrip(carBookRequest, location))正在调用时,我应该返回mocking tripdetails并跳过protoConverter.convertTrip(carBookRequest, location)方法调用。

ProtoRequestAdapterTest.java

@RunWith(PowerMockRunner.class)
@PrepareForTest({ProtoRequestAdapter})
class ProtoRequestAdapterTest {

    @Test
    public void testPopulateCarBookTest() {
        CarApiToProtoConverter carApiToProtoConverter;
        carApiToProtoConverter =  PowerMockito.mock(CarApiToProtoConverter.class);
        PowerMockito.when(carApiToProtoConverter.convertTripDetails(carBookRequest, locale)).thenReturn(tripDetails);
    }
}

ProtoRequestAdapter.java

class ProtoRequestAdapter {
     private CarBookRequest populateCarBook(BookingRequest bookingRequest) {
        CarBookRequest newCarBookReq = bookingRequest.getCarBookRequest();
        CarBookRequest.Builder carBookBuilder = CarBookRequest.newBuilder();

        ProtoConverter protoConverter =
                new ProtoConverter(refData, location);
        carBookBuilder.setTrip(protoConverter.convertTrip(carBookRequest, location));
        return carBookBuilder;
    }
}

1 个答案:

答案 0 :(得分:0)

您必须在测试类中实例化tripDetails

TripDetails tripDetails = new TripDetails();
tripDetails.setLocation = "London";