我无法使用 JUnit 5 和 Webflux 进行 Spring Rest Docs 测试。
我有一个像这样的 @WebFluxTest
的工作集成测试:
@WebFluxTest(SomeController.class)
class SomeControllerTest {
@Autowired
private WebTestClient testClient;
@MockBean
private SomeService service;
@Test
void testGetAllEndpoint() {
when(service.getAll())
.thenReturn(List.of(new Machine(1,"Machine 1", "192.168.1.5", 9060)));
testClient.get().uri("/api/machines")
.exchange()
.expectStatus().isOk()
.expectBodyList(Machine.class)
.hasSize(1);
}
}
我现在想写一个文档测试。根据文档,这样的事情应该有效:
@SpringBootTest
@ExtendWith({RestDocumentationExtension.class, SpringExtension.class})
class SomeControllerDocumentation {
private WebTestClient testClient;
@MockBean
private SomeService service;
@BeforeEach
public void setUp(WebApplicationContext webApplicationContext,
RestDocumentationContextProvider restDocumentation) {
this.testClient = WebTestClient.bindToApplicationContext(webApplicationContext)
.configureClient()
.filter(documentationConfiguration(restDocumentation))
.build();
}
@Test
void testGetAllEndpoint() {
when(service.getMachines())
.thenReturn(List.of(new Machine(1, "Machine 1", "192.168.1.5", 9060)));
testClient.get().uri("/api/machines")
.accept(MediaType.APPLICATION_JSON)
.exchange().expectStatus().isOk()
.expectBody().consumeWith(document("machines-list"));
}
}
但是我得到:
org.junit.jupiter.api.extension.ParameterResolutionException:
Failed to resolve parameter [org.springframework.web.context.WebApplicationContext webApplicationContext]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'org.springframework.web.context.WebApplicationContext' available:
expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
我还想知道是否需要 @SpringBootTest
作为注释,或者 @WebFluxTest(SomeController.class)
是否也应该工作。
我正在使用 Spring Boot 2.1.3 和 spring-restdocs-webtestclient
作为依赖项。
最佳答案
而不是注入(inject) WebApplicationContext
使用这个:
@Autowired
private ApplicationContext context;
@BeforeEach
void setUp(RestDocumentationContextProvider restDocumentation) {
client = WebTestClient.bindToApplicationContext(context)
.configureClient()
.filter(documentationConfiguration(restDocumentation))
.build();
}
关于java - JUnit 5 和 Webflux 的 Spring Rest 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55138027/