WebTestClient не вводится - PullRequest
       31

WebTestClient не вводится

0 голосов
/ 17 мая 2018

Прежде всего, я новичок в стеке Java, и в свою защиту я могу спросить кое-что глупое, спасибо за ваше терпение!

Что мне нужно:

Интеграционный тест, но без внешних запросов.Это означает, что мне нужно смоделировать зависимость где-то глубже в стеке, чем обычный модульный тест.Я также не хочу загружать весь стек в контексте.

Ожидается:

Умеет только издеваться над клиентом с @BeanMock и пройти тестовый проход,(Из моих испытаний это только издевается над первым уровнем глубины).

Факт:

С текущей настройкой я получаю

Error creating bean with name 'com.example.demo.SomeControllerTest': Unsatisfied dependency expressed through field 'webClient'

Если я использую @WebFluxTest(SomeController.class) и ContextConfiguration(...), клиент становится нулевым.Если я тогда добавлю, @TestConfiguration webflux жалуется на наличие аннотаций в конфликте, например @Configuration.

Любые идеи очень ценятся!

@RestController
public class SomeController {
  private final SomeService someService;

  @Autowired
  public SomeController(SomeService someService) {
    this.someService = someService;
  }


  @GetMapping(value = "/endpoint")
  public Mono<String> endpoint() {
    return someService.get();
  }
}


@Service
public class SomeService {
  private final Client client;

  @Autowired
  public SomeService(Client client) {
    this.client = client;
  }

  public Mono<String> get() {
    return client.build().get().retrieve().bodyToMono(String.class);
  }
}


@Component
public class Client {
  private final HttpServletRequest request;

  @Autowired
  public Client(HttpServletRequest request) {
    this.request = request;
  }

  public WebClient build() {
    return WebClient.builder()
      .baseUrl("https://httpstat.us/200")
      .build();
  }
}

@RunWith(SpringRunner.class)
@TestConfiguration
@SpringBootTest(classes = {
  SomeController.class,
  SomeService.class
})
@AutoConfigureWebTestClient
public class SomeControllerTest {
  @Autowired
  private WebTestClient webClient;

  @MockBean
  private Client client;


  @Before
  public void setUp() {
    when(client.build())
      .thenReturn(WebClient.create("https://httpstat.us/201"));
  }

  @Test
  public void deepMocking() {
    webClient.get()
      .uri("/endpoint")
      .exchange()
      .expectStatus().isOk()
      .expectBody(String.class).isEqualTo("201 Created");
  }
}

Ответы [ 2 ]

0 голосов
/ 17 мая 2018
@RunWith(SpringRunner.class)
@WebFluxTest(SomeController.class)
@ContextConfiguration(classes = {
   SomeController.class,
   SomeService.class
 })
 public class SomeControllerTest {
   @Autowired
   private WebTestClient webClient;
   // ...
 }

Это обязательное комбо, но я не понимаю, зачем нужно добавлять SomeController.class в активный контекст, разве @WebFluxTest тоже не делает этого?

OR

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
  SomeController.class,
  SomeService.class,
})
// @AutoConfigureWebTestClient // does absolutely nothing?
public class SomeControllerTest {
  @Autowired
  private SomeController controller;

  // ...

  @Test
  public void deepMocking() {
    WebTestClient.bindToController(controller)
      .build()
      .get()
      .uri("/endpoint")
      .exchange()
      .expectStatus().isOk()
      .expectBody(String.class).isEqualTo("201 Created");
  }
}
0 голосов
/ 17 мая 2018

ошибка говорит о том, что вы получаете сообщение об ошибке при попытке автоматического связывания bean-компонента WebTestClient внутри класса SomeControllerTest, вы не можете просто автоматически связать WebTestClient, его нужно изменить на

WebTestClient testClient = WebTestClient
  .bindToServer()
  .baseUrl("http://localhost:8080")
  .build();

Вы можете найти больше о WebClient из этой статьи http://www.baeldung.com/spring-5-webclient

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...