【发布时间】:2017-09-06 11:33:43
【问题描述】:
我有 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);
}
}
}
【问题讨论】:
-
您不能为此使用
MockMvc。MockMvc在内部拥有一个特定的DispatcherServlet,旨在用于 Spring MVC 测试(即存在于DispatcherServlet中的所有内容)。
标签: java spring servlets junit spring-boot-test