gpt4 book ai didi

spring - WebTestClient 未注入(inject)

转载 作者:行者123 更新时间:2023-12-02 03:33:23 25 4
gpt4 key购买 nike

首先,我是 Java 堆栈的新手,为我辩护,我可能会问一些愚蠢的问题,谢谢您的耐心!

我需要什么:

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

预期:

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

实际:

根据当前的设置,我得到了

创建名称为“com.example.demo.SomeControllerTest”的 bean 时出错:通过字段“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");
}
}

关于spring - WebTestClient 未注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50398616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com