首先,我是Java堆栈的新手,为了防御起见,我可能会问一些愚蠢的事情,谢谢您的耐心等待!

我需要的:

集成测试,但不发出外部请求。这意味着我必须在堆栈中比普通单元测试更深的地方模拟依赖项。
我也不想在上下文中加载所有堆栈。

预期:

只能使用@BeanMock模拟客户端并通过测试。 (根据我的试验,这只会嘲笑第一级深度)。

实际:

使用当前设置,我得到

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

如果我使用@WebFluxTest(SomeController.class)ContextConfiguration(...),则客户端最终将为null。如果再添加@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");
  }
}

最佳答案

@RunWith(SpringRunner.class)
@WebFluxTest(SomeController.class)
@ContextConfiguration(classes = {
   SomeController.class,
   SomeService.class
 })
 public class SomeControllerTest {
   @Autowired
   private WebTestClient webClient;
   // ...
 }


这是必需的组合,但是我不明白为什么要在活动上下文中添加SomeController.class的原因,@WebFluxTest也不能这样做吗?

要么

@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");
  }
}

09-17 21:36