Spring Boot 404错误提示

k2fxgqgv  于 2022-11-05  发布在  Spring
关注(0)|答案(1)|浏览(263)

我有一个应用程序,它将所有无效路径重定向到swagger页面,如下所示:

@Configuration
public class MyProjectContext implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController(Endpoints.NOT_FOUND)
            .setViewName("redirect:" + Endpoints.SWAGGER);
    }

    @Bean
    public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
        return container -> {
            container.addErrorPages(
                new ErrorPage(HttpStatus.NOT_FOUND, Endpoints.NOT_FOUND)
            );
        };
    }

}

现在我想测试一下。为此,我写了一个测试,如下所示:

@AutoConfigureTestEntityManager
@SpringBootTest
@ContextConfiguration(classes = { MyProjectContext.class })
@AutoConfigureMockMvc
class MyProjectErrorControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void errorEnpointShouldRedirectToSwaggerPage() throws Exception {
        mockMvc.perform(get("/dfhdfth"))
            .andExpect(redirectedUrl(Endpoints.SWAGGER));
    }
}

但是,由于以下原因,该测试目前失败:

java.lang.AssertionError: Redirected URL expected:</swagger-ui/index.html> but was:<null>

另外,下面是Request和Response的控制台输出:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /dfhdfth
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {}

Handler:
             Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

我可以想象这是因为我在这里使用了MockMvc。是这样吗?如果是这样,我如何“正确”地编写它?

qkf9rpyu

qkf9rpyu1#

好了,我现在设法让它工作如下:
首先,我将webflux依赖项添加到我的build.gradle,如下所示:

testImplementation 'org.springframework.boot:spring-boot-starter-webflux'

然后,我使用WebTestClient编写测试,如下所示:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.reactive.server.WebTestClient;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
class ErrorControllerTest {

    @Autowired
    private WebTestClient webTestClient;

    @Test
    void errorEnpointShouldRedirect() throws Exception {
        webTestClient.get()
            .uri("/garxms")
            .exchange()
            .expectStatus()
            .isEqualTo(HttpStatus.FOUND);
    }

    @Test
    void errorEnpointShouldRedirectToSwaggerPage() throws Exception {
        webTestClient.get()
            .uri("/garxms")
            .exchange()
            .expectHeader()
            .valueMatches("Location", ".*" + Endpoints.SWAGGER);
    }
}

就像一个魅力。

相关问题