其他分享
首页 > 其他分享> > 使用MockMVC测试Spring 4.0.3控制器(MVC)

使用MockMVC测试Spring 4.0.3控制器(MVC)

作者:互联网

我正在尝试为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,它就像预期的那样运行.

网址 – > HTTP://本地主机:8080 /应用程序名称/ REST /媒体

现在我想为这个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

解决方法:

您需要将init更改为:

 mockMvc = MockMvcBuilders.standaloneSetup(new MediaListController()).build();

标签:spring-test-mvc,spring,spring-mvc,integration-testing
来源: https://codeday.me/bug/20190728/1562839.html