我有一个 MockMvc 测试,我在测试启动时动态添加静态内容。我有下面的 2 个测试,其中 CSS 文件的测试通过了,
index.html
文件的测试没有通过。
@SpringBootTest
@AutoConfigureMockMvc
class FrontEndForwardControllerTest {
@TempDir
private static File tempDir;
@Test
void should_return_index() throws Exception {
// GIVEN
val indexFile = new File(tempDir, "index.html");
Files.writeString(indexFile.toPath(), "<!DOCTYPE html><html></html>");
// WHEN
mockMvc.perform(get("/"))
// THEN
.andExpect(status().isOk());
}
@Test
void should_match_static_content_when_url_contains_dot() throws Exception {
// GIVEN
val testStylesDir = new File(tempDir, "test-styles");
testStylesDir.mkdirs();
val cssFile = new File(testStylesDir, "some.css");
Files.writeString(cssFile.toPath(), "body {}");
// WHEN
mockMvc.perform(get("/test-styles/some.css"))
// THEN
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(new MediaType("text", "css")));
}
@TestConfiguration
public static class StaticResourceConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/**")
.addResourceLocations(tempDir.toURI().toString());
}
}
这是我正在测试的控制器:
@Controller
public class FrontEndForwardController {
@GetMapping(value = "/**/{path:[^.]*}")
public String redirect(HttpServletRequest request) {
return "forward:/";
}
}
控制器背后的想法是拥有一个 SPA 应用程序,由 Spring Boot 提供服务。