我正在尝试编写一些测试,当我尝试post
一个字节数组体时,我面临以下异常:
错误
java.lang.AssertionError: Status expected:<201> but was:<404>
> POST /api/foo
> WebTestClient-Request-Id: [1]
> Content-Length: [246444]
Content not available yet
< 404 Not Found
<
Content not available yet
My Test课程如下:
@AutoConfigureWebTestClient
@RunWith(SpringRunner.class)
@FixMethodOrder(NAME_ASCENDING)
@SpringBootTest(classes = Application.class)
public class ControllerTest {
@Inject
protected WebTestClient webClient;
@Test
public void testPostFile() throws Exception {
byte[] bytes;
try (InputStream is = getClass().getClassLoader().getResourceAsStream("static/binary-file.docx")) {
bytes = IOUtils.toByteArray(is);
}
webClient
.post()
.uri("/api/foo")
.body(BodyInserters.fromResource(new ByteArrayResource(bytes))))
.exchange()
.expectStatus().isCreated();
}
}
是否有人面临同样的问题,似乎无法正确加载资源
修改
我的应用程序引导类
@EnableWebFlux
@Configuration
@ComponentScan(basePackageClasses = SBApplication.class)
@EnableAutoConfiguration
public class SBApplication {
/**
* Spring Boot Main Entry
*
* @param args command line arguments
* @throws Exception on failure
*/
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext ctx = new SpringApplicationBuilder()
.sources(SBApplication.class)
.run(args);
}
}
我的控制器类:
@RestController
@RequestMapping("/api")
public class SBController {
// ...
@RequestMapping(
method = POST,
path = "{name}"
)
public Mono<ResponseEntity> store(
@PathVariable("name") String name,
@RequestBody byte[] body) {
// do stuff
return Mono.just(
ResponseEntity
.status(HttpStatus.CREATED)
.build()
);
}
}
答案 0 :(得分:1)
最终,问题是我的Controller是通过注释配置的。 WebTestClient只能识别通过RouterFunction
路由的映射端点。
为了测试配置了注释(例如我的示例)的Controller,您需要初始化MockMvc并使用相应的注释@AutoConfigureMockMvc
最后,由于使用reactor-core
,我们需要使用MockMvcRequestBuilders.asyncDispatch
,如下所示:
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
@FixMethodOrder(NAME_ASCENDING)
@SpringBootTest(classes = Application.class)
public class ControllerTest {
@Inject
protected MockMvc mockMvc;
@Test
public void testPostFile() throws Exception {
byte[] bytes;
try (InputStream is = getClass().getClassLoader().getResourceAsStream("static/binary-file.docx")) {
bytes = IOUtils.toByteArray(is);
}
MvcResult result = mockMvc.perform(
post("/api/foo")
.content(bytes)
)
.andExpect(request().asyncStarted())
.andReturn();
mockMvc.perform(asyncDispatch(result))
.andExpect(status().isCreated());
}
}
最后一切都按预期工作!