Mockito模拟restTemplate不使用返回模拟值

时间:2019-07-17 21:57:49

标签: java junit mockito resttemplate

以下相关代码:

服务代码:

@RunWith(MockitoJUnitRunner.class)
public class PartnerFulfillmentServiceImplTest {

@Mock
RestTemplate restTemplate;

@Mock
HttpHeaders httpHeaders;

@Mock
ResponseEntity responseEntity;

@InjectMocks
PartnerFulfillmentServiceImpl partnerFulfillmentService;

@Test
public void createAppointmentTest() {

    Whitebox.setInternalState(partnerFulfillmentService, "internalServiceUrl", "http://localhost:8080");

    AppointmentRequest appointmentRequest = new AppointmentRequest();
    appointmentRequest.setPartnerName("CENTRICITY");
    appointmentRequest.setTicketNumber("123ABC");

    httpHeaders = new HttpHeaders();
    httpHeaders.set("Content-type", "application/json");

    responseEntity = new ResponseEntity<>(
            "some response body",
            HttpStatus.OK
    );

    when(restTemplate.exchange(Mockito.anyString(),
            Mockito.<HttpMethod> any(),
            Mockito.<HttpEntity<?>> any(),
            Mockito.<Class<Object>> any()))
            .thenReturn(responseEntity);

    ResponseEntity<AppointmentResponse> response = partnerFulfillmentService.createAppointment(appointmentRequest);

    Assert.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
}

测试代码:

.thenReturn(responseEntity);

我正在 java.lang.AssertionError: 预期:500 实际的:200  之所以可以理解,是因为它实际上并不是在调用运行public abstract class Fictional<A extends Fictional> { public ArrayList<A> subclassArray = new ArrayList<A>(); int i; public Fictional(int i) { this.i = i; } public A loadFromFile() //I wouldn't have to override this method { A subclass = this.build(1); //it's not possible to make new instance of abstract class, but it would be possible with any other subclass subclassList.put(subclass); return subclass; } protected abstract A build(int i); } class Real extends Fictional { public Real(int i) { super(i); } @Override protected Fictional build(int i) { return new Real(i); } } 的逻辑。我的百万美元问题是,为什么?它应该返回responseEntity值。我拥有将exchange()转换为any()的所有参数,希望能够尽可能经常地触发条件,因为我总是可以在不同的时间缩小条件。我没有正确嘲笑我的restTemplate吗?这是我目前对正在发生的事情的怀疑。任何建议都会有所帮助!

谢谢!

1 个答案:

答案 0 :(得分:1)

就像@JB Nizet指出的那样,您正在测试的方法中创建RestTemplate的新实例。这意味着将从新实例中调用exchange方法,而不是模拟方法。如果包含方法createAppointment的类的依赖项注入为RestTemplate,则可以按照实现的方式实现它。

您想要的是模拟RestTemplate新实例的构造函数,以便在创建新实例时将其替换。不幸的是,Mockito无法模拟构造函数,因此您应使用PowerMockito来模拟构造函数。

whenNew(RestTemplate.class).withNoArguments().thenReturn(restTemplate);

responseEntity = new ResponseEntity<>(
            "some response body",
            HttpStatus.OK
    );

when(restTemplate.exchange(Mockito.anyString(),
        Mockito.<HttpMethod> any(),
        Mockito.<HttpEntity<?>> any(),
        Mockito.<Class<Object>> any()))
        .thenReturn(responseEntity);