gpt4 book ai didi

java - Spring Boot 测试无法识别 servlet

转载 作者:太空宇宙 更新时间:2023-11-04 11:10:26 25 4
gpt4 key购买 nike

我有 Spring Boot 应用程序,我想测试它。我不使用 Spring Controller ,但我使用带有服务方法的 Servlet。我还有提供 ServletRegistrationBean 的配置类。但每次当我尝试执行模拟请求时,我都会收到 404 错误。根本没有调用servlet。我认为Spring没有找到这个servlet。我该如何解决它?当我在本地主机启动应用程序时,一切正常。

测试:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class SpringDataProcessorTest {

@Autowired
private MockMvc mockMvc;

@Test
public void retrieveByRequest() throws Exception{
mockMvc.perform(buildRetrieveCustomerByIdRequest("1")).andExpect(status().isOk());

}

private MockHttpServletRequestBuilder buildRetrieveCustomerByIdRequest(String id) throws Exception {
return get(String.format("/path/get('%s')", id)).contentType(APPLICATION_JSON_UTF8);
}
}

配置:

@Configuration
public class ODataConfiguration extends WebMvcConfigurerAdapter {
public String urlPath = "/path/*";


@Bean
public ServletRegistrationBean odataServlet(MyServlet servlet) {
return new ServletRegistrationBean(servlet, new String[] {odataUrlPath});
}
}

MyServlet:

@Component
public class MyServlet extends HttpServlet {

@Autowired
private ODataHttpHandler handler;


@Override
@Transactional
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
handler.process(req, resp);
} catch (Exception e) {
log.error("Server Error occurred", e);
throw new ServletException(e);
}
}
}

最佳答案

如果您确实想使用 MockMvc 而不是 Servlet 来测试您的代码,请使用 HttpRequestHandler 并使用 SimpleUrlHandlerMapping 将其映射到 URL。

类似下面的内容。

@Bean
public HttpRequestHandler odataRequestHandler(ODataHttpHandler handler) {
return new HttpRequestHandler() {
public void handleRequest() {
try {
handler.process(req, resp);
} catch (Exception e) {
log.error("Server Error occurred", e);
throw new ServletException(e);
}
}
}
}

以及映射

@Bean
public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setUrlMap(Collections.singletonMap(odataUrlPath, "odataRequestHandler");
return mapping;
}

另一个解决方案是将其包装在 Controller 而不是 servlet 中。

@Controller
public class ODataController {

private final ODataHttpHandler handler;

public ODataController(ODataHttpHandler handler) {
this.handler=handler;
}

@RequestMapping("/path/*")
public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException {
try {
handler.process(req, resp);
} catch (Exception e) {
log.error("Server Error occurred", e);
throw new ServletException(e);
}
}
}

无论哪种方式,您的处理程序都应该由 DispatcherServlet 提供/处理,因此可以使用 MockMvc 进行测试。

关于java - Spring Boot 测试无法识别 servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46074131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com