栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何让Spring MVC在JUnit测试中调用验证?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何让Spring MVC在JUnit测试中调用验证?

验证是在调用控制器之前完成的,因此您的测试不会调用此验证。

还有另一种测试控制器的方法,您不直接调用控制器。相反,您可以构造并调用控制器映射到的URL。这是一个很好的例子:http : //rstoyanchev.github.com/spring-31-and-mvc-
test/#1

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(loader=WebContextLoader.class, locations = {"classpath:/meta-INF/spring/applicationContext.xml", "classpath:/meta-INF/spring/applicationContext-test-override.xml", "file:src/main/webapp/WEB-INF/spring/webmvc-config.xml"})public class MyControllerTest {@AutowiredWebApplicationContext wac;MockMvc mockMvc;@Beforepublic void setup() {    this.mockMvc = MockMvcBuilders.webApplicationContextSetup(this.wac).build();}@Test@Transactionalpublic void testMyController() throws Exception {    this.mockMvc.perform(get("/mycontroller/add?param=1").accept(MediaType.TEXT_HTML))    .andExpect(status().isOk())    .andExpect(model().attribute("date_format", "M/d/yy h:mm a"))    .andExpect(model().attribute("myvalue", notNullValue()))    .andExpect(model().attribute("myvalue", hasSize(2)))    .andDo(print());}}

POM(需要使用spring里程碑回购):

    <!-- required for spring-test-mvc -->    <repository>        <id>spring-maven-milestone</id>        <name>Spring Maven Milestone Repository</name>        <url>http://maven.springframework.org/milestone</url>    </repository>...    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-test-mvc</artifactId>        <version>1.0.0.M1</version>        <scope>test</scope>    </dependency>

注意:spring-mvc-test库尚未准备就绪。实施中存在一些差距。我认为计划在3.2spring全面实施。

这种方法是一个好主意,因为它可以完全测试您的控制器。它很容易弄乱您的控制器映射,因此确实需要对它们进行单元测试。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/430522.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号