java Spring启动测试无法识别servlet
我有Spring Boot应用程序,我想测试它。我不使用Spring控制器,但我使用Servlet和服务方法。我还有一个配置类,它提供ServletRegistrationBean。 但每次我尝试执行模拟请求时,都会出现404错误。根本不需要调用servlet。我认为Spring没有找到这个servlet。我该怎么修?当我在localhost上启动应用程序时,一切正常
测试:
@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);
}
}
}
# 1 楼答案
如果你真的想用
MockMvc
而不是Servlet
来测试你的代码,那就用HttpRequestHandler
和SimpleUrlHandlerMapping
来把它映射到一个URL类似于下面的内容
还有地图
另一个解决方案是将其封装在控制器中,而不是servlet中
无论哪种方式,你的处理程序都应该由
DispatcherServlet
提供服务/处理,因此可以使用MockMvc
进行测试