【问题标题】:Testing Spring 4.0.3 Controller (MVC) with MockMVC使用 MockMVC 测试 Spring 4.0.3 控制器 (MVC)
【发布时间】:2014-05-31 06:36:31
【问题描述】:

我正在尝试为 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 --&gt; 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

【问题讨论】:

  • MockMvcBuilders.standaloneSetup 接受控制器,而不是类。
  • 尝试“媒体”而不是“/媒体”

标签: spring spring-mvc integration-testing spring-test-mvc


【解决方案1】:

您需要将您的 init 更改为:

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

【讨论】:

  • 您好,感谢您的快速响应,我进行了您提到的更改,现在我遇到了不同的异常。 org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoSuchMethodError: javax.servlet.http.HttpServletResponse.getHeader(Ljava/lang/String;)Ljava/lang/String;
  • 是的,我看到了我的 maven 依赖项,它同时具有 2.5 和 3.0 servlet-api。我删除了 2.5 依赖项,它的工作正常。
  • 如果 MediaListController 类中有自动装配字段怎么办?如果使用 new 运算符,Spring 似乎不会自动装配字段?我按照你说的做了,但是发生了错误,因为控制器中用@Resource 标记的字段无法自动装配。
猜你喜欢
  • 1970-01-01
  • 2014-01-25
  • 2013-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多