我有Spring Boot Application,我想測試它。我不使用Spring控制器,但我使用服務方法的Servlet。另外我有我的配置類,提供ServletRegistrationBean。 但每次我嘗試執行模擬請求時,都會收到404錯誤。根本沒有對servlet的調用。我認爲Spring沒有找到這個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'。 'MockMvc'在內部保存了一個特定的'DispatcherServlet',並且旨在用於Spring MVC測試(意味着存在於'DispatcherServlet'中的所有東西)。 –