макет запроса объекта вызова для модульного теста - PullRequest
1 голос
/ 25 марта 2019

Я хочу смоделировать объект запроса и ответ, чтобы проверить метод на методе контроллера, этот код был написан другим разработчиком, и я должен проверить его с помощью mockito. Я издеваюсь над классом контроллера

Я пытаюсь смоделировать значение объекта запроса и значение объекта ответа, но это не работает, и я получаю ошибку отражения, когда пытаюсь отладить

    public class InquiryController {

private static final Logger log = 
    LoggerFactory.getLogger(InquiryController.class);

@Autowired
private InquiryProperties inquiryProperties;

@Autowired
private InquiryService inquiryService;


@Autowired
RestTemplate restTemplate;

public static int count = 0;


@Bean
private RestTemplate getRestTemplate() {
    return new RestTemplate();
}

    @PostMapping(value = "/endCustomer", produces = { MediaType.APPLICATION_JSON_VALUE }, consumes = {
        MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<List<EndCustomerDTO>> endCustomer(@RequestBody CustomerInfo customerInfo)
        throws IOException, JSONException {

    log.info("### InquiryController.endCustomer() ===>");
    List<EndCustomerDTO> endCustomerDTOs = null;

    try {

        //RestTemplate restTemplate = new RestTemplate();
        RequestEntity<CustomerInfo> body = RequestEntity.post(new URI(inquiryProperties.getEndCustomer()))
                .accept(MediaType.APPLICATION_JSON).body(customerInfo);
        ResponseEntity<List<EndCustomerDTO>> response = restTemplate.exchange(body,
                new ParameterizedTypeReference<List<EndCustomerDTO>>() {
                });
        endCustomerDTOs = (response != null ? response.getBody() : new ArrayList<EndCustomerDTO>());

    } catch (RestClientException | URISyntaxException e) {
        log.error("InquiryController.endCustomer()" + e.getMessage());
    }

    log.info("### END InquiryController.endCustomer()  ===>");

    if (null == endCustomerDTOs) {
        return new ResponseEntity<List<EndCustomerDTO>>(new ArrayList<EndCustomerDTO>(), HttpStatus.OK);
    }
    return new ResponseEntity<List<EndCustomerDTO>>(endCustomerDTOs, HttpStatus.OK);

}

Ответы [ 2 ]

0 голосов
/ 25 марта 2019

После того, как вы отделите конфигурацию от контроллера, как предложено @chrylis, вы продолжите в том же духе.

Вы должны пытаться смоделировать метод RequestEntity.post. Обратите внимание, что это статический метод, и он немного отличается от обычных методов экземпляра public. Для этого вам нужно использовать PowerMockito, так как Mockito не подойдет.

добавить зависимость в pom следующим образом:

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>1.6.5</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.6.5</version>
    <scope>test</scope>
</dependency>

затем аннотируйте тестовый класс с помощью @RunWith и @PrepareForTest примерно так:

@RunWith(PowerMockRunner.class)
@PrepareForTest({RequestEntity.class})
public class TestClass {
}

и смоделируйте метод post следующим образом:

PowerMockito.mockStatic(RequestEntity.class);  when(RequestEntity.post(any(URI.class))).thenReturn(getRequestEntityResponseBody());
private RequestEntity< CustomerInfo > getRequestEntityResponseBody(){
 //code
}

UPDATE

CustomerInfo customerInfo = new CustomerInfo();
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue");
RequestEntity<CustomerInfo> customerInfoRequestEntity = new ResponseEntity<CustomerInfo>(customerInfo, responseHeaders, HttpStatus.OK);
PowerMockito.mockStatic(RequestEntity.class);
when(RequestEntity.post(any(URI.class))).thenReturn(customerInfoRequestEntity);
0 голосов
/ 25 марта 2019

Это потому, что экземпляр RestTemplate не вводится через Spring IOC, когда вы выполняете вызов REST. Вам необходимо объявить метод getRestTemplate в классе компонента, который сканируется во время запуска приложения или другими словами во время сканирования компонента. Таким образом, restTemplate доступно для autowire.

...