我正在尝试为RestController创建测试用例。这是一个简单的RestContorller
@RestController
@RequestMapping("/media")
public class MediaListController {
@RequestMapping(method = RequestMethod.GET)
public String getAllMedia(){
return "TEST COMPLETE";
}
}
我的spring-rest-servlet.xml
文件有<mvc:annotation-driven />
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.mp.web.controller.common" />
</beans>
现在,如果我在tomcat 8上部署我的WAR,就会按预期运行。
URL --> http://localhost:8080/application-name/rest/media
现在我想为此REST服务创建一个测试用例。到目前为止我做了什么
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:spring-rest-servlet.xml")
public class MediaTest {
MockMvc mockMvc;
@Before
public void init(){
mockMvc = MockMvcBuilders.standaloneSetup(MediaListController.class).build();
}
@Test
public void getAllMediaTest1() throws Exception {
mockMvc.perform(get("/media")).andExpect(status().isOk());
}
}
如果我运行该测试,我会收到以下警告。
WARN o.s.w.s.PageNotFound - No mapping found for HTTP request with URI [/media] in DispatcherServlet with name ''
我尝试了与
等其他选项的链接'/' , '/rest/media' , 'http://localhost:8080/app-name/rest/media'
但没有用。
我正在使用Spring 4.0.3
答案 0 :(得分:7)
您需要将init更改为:
mockMvc = MockMvcBuilders.standaloneSetup(new MediaListController()).build();