1

我需要模拟以下方法调用carBookBuilder.setTrip(protoConverter.convertTrip(carBookRequest, location)),但是当carBookBuilder.setTrip(protoConverter.convertTrip(carBookRequest, location))调用时我应该只返回模拟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;
    }
}
4

2 回答 2

1

我在这里看到了几个问题。如果我理解正确,您正在尝试测试 ProtoRequestAdapter#populateCarBook.

首先,您应该将该方法公开或至少受保护,否则您的单元测试无法调用它。

接下来您要模拟的方法是ProtoConverter#convertTrip,它不是私有的,否则您的代码将无法编译。更大的问题是您直接在代码中实例化它,这使得无法用模拟替换它。

我强烈建议你将它注入你的类(或者至少将实例化移动到一个(受保护的)getProtoConverter()方法中,你可以在你的测试中覆盖它)。

于 2015-07-15T09:04:03.780 回答
0

你必须tripDetails在你的测试类中实例化。

TripDetails tripDetails = new TripDetails();
tripDetails.setLocation = "London";
于 2015-07-15T07:25:03.880 回答