我正在尝试编写一些测试并面对以下异常,当我尝试 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
我的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();
}
}
是否有人面临同样的问题,似乎无法正确加载资源
EDIT:
我的应用程序Bootstrap类
@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()
);
}
}
1 回答
最终,问题是我的控制器是通过注释配置的 . WebTestClient只能识别通过
RouterFunction
路由的映射 endpoints .为了测试配置了注释的Controller,例如我的示例,您需要初始化MockMvc并使用相应的注释
@AutoConfigureMockMvc
最后,由于使用了
reactor-core
,我们需要使用MockMvcRequestBuilders.asyncDispatch
如下:最后一切都按预期工作!