spring - WebTestClient 未注入
问题描述
首先,我是 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");
}
}
解决方案
@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");
}
}
推荐阅读
- go - 路径中的 golang 和 go-socket.io 参数
- google-apps-script - Google Apps 脚本 - setRichTextValue() 异常可能由 for 循环引起
- flutter - 如何将 ListWheelScrollView 定位到给定的索引?
- python - rasa 和 rasa X 安装错误并运行本地服务器
- php - 无法再次安装 cakephp 4
- json - Powershell 5.1 解析特定键的 json,并将其值作为行分隔文本写入新的 .txt 文件
- javascript - 前后端连接 | 节点.Js , Javascript
- python - 我有两个列表,如何让它们一个一个地计时?
- c# - Visual Studio 2019 中的调试问题 - C#
- azure - 将 Azure Function 的输出设置为 Cosmos DB 后出现 404