Я пытаюсь понять, как использовать WebTestClient.bindToController().
У меня есть следующие 2 класса:
Controller.methodx() вызывает Service.methody(). Service.methody() вызывает внешнюю конечную точку REST POST.
Как мне использовать WebTestClient.bindToController() для тестирования этого контроллера? Я не мог найти много информации об использовании в Интернете.
Контроллер:
@RestController
@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class CustomerController {
@Autowired
private CustomerService customerService;
@PostMapping(value = "/customer", consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
public Mono<Customer> saveCustomer(@RequestBody Customer customer){
return this.customerService.saveCustomer(customer);
}
Оказание услуг:
@Service
public class CustomerService implements ICustomerService {
@Autowired
private WebClient webClient;
@Override
public Mono<Customer> storeMessage(Customer cust) {
Mono<Customer> resp = this.webClient.post()
.uri("/postdata")
.body(BodyInserters.fromObject(customer))
.exchange();
return resp
}
}
КОНФИГУРАЦИЯ:
@Configuration
public class ProdConfig {
@Bean
public ICustomerService getCustomerService() {
return new CustomerService();
}
@Bean
public WebClient getWebClient() {
return WebClient.builder()
.baseUrl("baseurl")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MIME_TYPE)
.defaultHeader(HttpHeaders.USER_AGENT, USER_AGENT)
.build();
}
}
ТестКласс:
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = TestConfig.class)
@AutoConfigureMockMvc
public class CustomerControllerTest {
@MockBean
private CustomerService customerservice;
private WebTestClient testClient;
@Test
public void testSaveCustomer() throws Exception {
testClient= WebTestClient.bindToController(new CustomerController(customerService)).build();
testClient.post().uri("/customer").body(BodyInserters.fromObject(customer))
.exchange()
.expectStatus().is2xxSuccessful();
}
}
ТЕСТКОНФИГ:
@Profile("test")
@Configuration
@EnableAutoConfiguration
public class TestConfig {
@Bean
public WebClient getWebClient() {
return WebClient.builder()
.baseUrl("baseurl")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MIME_TYPE)
.defaultHeader(HttpHeaders.USER_AGENT, USER_AGENT)
.build();
}
}
Ошибка при запуске тестового класса:
org.springframework.test.context.TestContextManager[0;39m: Caught exception while invoking 'afterTestMethod' callback on
TestExecutionListener [org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@61df66b6] for test method
[public void CustomerControllerTest.testSaveCustomer()] and test instance
[CustomerControllerTest@22da200e]
java.lang.NoSuchMethodError: org.mockito.MockingDetails.getMockCreationSettings()Lorg/mockito/mock/MockCreationSettings;
at org.springframework.boot.test.mock.mockito.MockReset.get(MockReset.java:107)
WebTestClient internally uses WebClient to perform requests. Instead of providing a base url to make the request, we can simply bind the controller to the WebTestClient to handle the request mappings.
CustomerController.java
@RestController
@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class CustomerController {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private CustomerService customerService;
public CustomerController( CustomerService customerService) {
this.customerService = customerService;
}
@PostMapping(value = "/customer", consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
public Mono<Customer> saveCustomer(@RequestBody Customer customer){
return this.customerService.saveCustomer(customer);
}
CustomerControllerTest.java
@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerControllerRestTest {
private WebTestClient testClient;
@MockBean
private CustomerService customerService;
@Before
public void setup() {
//mock service here
}
@Test
public void testSaveCustomer() throws Exception {
Customer customer = new Customer(1L, "test", CustomerGender.MALE);
testClient= WebTestClient.bindToController(new CustomerController(customerService)).build();
testClient.post().uri("/customer").body(BodyInserters.fromObject(customer))
.exchange()
.expectStatus().is2xxSuccessful();
}
}
Проблема в ваших зависимостях, используйте spring boot 2.x.x.
моя весенняя загрузочная версия - 2.1.2.RELEASE.
Это из-за проблемы с зависимостями пути к классу. Проверьте свою помпу
мои зависимости объектов немного отличаются от вашего примера. Когда я настраиваю свой тестовый класс, как вы предложили, я получаю сообщение об ошибке. Я отредактирую свой пост, чтобы добавить подробности.