spring - 使用 MockMVC 测试 Spring 4.0.3 Controller (MVC)

标签 spring spring-mvc integration-testing spring-test-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,它就会按预期运行。

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

最佳答案

您需要将 init 更改为:

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

关于spring - 使用 MockMVC 测试 Spring 4.0.3 Controller (MVC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23108585/

相关文章:

spring webflow 'Property not found'异常

java - 在应用程序启动之前配置@MockBean 组件

spring - cvc-complex-type.2.4.c : The matching wildcard is strict, 但找不到元素 'context:property-placeholder' 的声明

c# - 使用依赖注入(inject)的现实世界解决方案

java - 如何获取Spring上下文

java - Hibernate 中的继承。插入示例

java - server.port 和 server.context-path 在部署到 tomcat 时不生效

java - 我是否需要为每个测试创建一个新的 MockMvc?

c# - 使用 nhibernate 在 .net 中进行集成测试

java - Spring-boot,JUnit 测试使用不同的配置文件