我在测试我的自定义 registrationDispatcherServlet 时遇到问题。
我用 bean 创建了配置类:
@Configuration
public class ServletDispatcherInitializer {
@Bean
public ServletRegistrationBean registrationDispatcherServlet(ApplicationContext parentApplicationContext) {
AnnotationConfigWebApplicationContext childApplicationContext = new AnnotationConfigWebApplicationContext();
childApplicationContext.setParent(parentApplicationContext);
childApplicationContext.register(WebApiConfig.class);
DispatcherServlet dispatcherServlet = new DispatcherServlet();
dispatcherServlet.setApplicationContext(childApplicationContext);
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(dispatcherServlet, "/api/v1/*");
servletRegistrationBean.setLoadOnStartup(0);
servletRegistrationBean.setName("customDispatcherServlet");
return servletRegistrationBean;
}
}
使用一些注释创建 WebApiConfig 类:
@EnableWebMvc
@Configuration
@ComponentScan("info.pionas.rental")
public class WebApiConfig {
}
这是我的 StubRestController:
@RestController
@RequestMapping("/stub")
public class StubRestController {
@GetMapping
public String test() {
return "Super";
}
}
在测试时我跳过前缀它有效但如果我添加前缀它不起作用
@SpringBootTest
@AutoConfigureMockMvc
class StubRestControllerTest extends Specification {
@Autowired
private MockMvc mockMvc
def "should return exist page"() {
expect:
mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/stub/test")) // not works
.andExpect(MockMvcResultMatchers.status().is(HttpStatus.OK.value()))
}
}
有什么想法吗?
感谢帮助