使用动态插入静态文件的 MockMvc 进行 Spring Boot 测试

问题描述 投票:0回答:0

我有一个 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 提供服务。

spring-boot spring-boot-test mockmvc
© www.soinside.com 2019 - 2024. All rights reserved.