我有一个应用程序,它将所有无效路径重定向到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。是这样吗?如果是这样,我如何“正确”地编写它?
1条答案
按热度按时间qkf9rpyu1#
好了,我现在设法让它工作如下:
首先,我将webflux依赖项添加到我的
build.gradle
,如下所示:然后,我使用
WebTestClient
编写测试,如下所示:就像一个魅力。