Spring MVC的测试

  测试是保证软件质量的关键。

  与 Spring MVC 相关的测试,主要涉及控制器的测试。

  为了测试Web项目通常不需要启动项目,需要一些Servlet相关的一些模拟对象,比如MockMVC、MockHttpServletRequest、MockHttpServletResponse、MockHttpSession等。

  Spring 里,使用 @WebAppConfiguration 指定加载的 ApplicationContext 是一个 WebApplicationContext

  

  测试驱动开发(Test Driven Development ,TDD),先按照需求写一个满足自己预期结果的测试用例,这个测试用例刚开始是失败的测试,随着不断的编码和重构,最终让测试用例通过测试,这样可以保证软件的质量和可控性。

  在 Spring Web程序中使用集成测试:

  首先导入两个测试依赖的包(spring-test、junit):

    

 1 <properties>
 2     <junit.version>4.11</junit.version>
 3     <spring.version>4.0.6.RELEASE</spring.version>
 4 </properties>
 5 <!-- 测试相关jar包 -->
 6 <dependency>
 7     <groupId>junit</groupId>
 8     <artifactId>junit</artifactId>
 9     <version>${junit.version}</version>
10     <scope>test</scope>
11 </dependency>
12 <dependency>
13     <groupId>org.springframework</groupId>
14     <artifactId>spring-test</artifactId>
15     <version>${spring.version}</version>
16     <scope>test</scope>
17 </dependency>

  然后了解一下包结构(点击这里,教你如何在IDEA中建立并修改包结构),就是把 test.class写在哪儿,在哪里执行。

  

  在这里,src/main 目录下的文件是程序运行的主文件,而src/test下的文件,是程序测试的运行文件。

  接下来就可以在src/test/java包下新建一个测试类的。

  在空测试类上,需要有如图的三个注解符号

   @RunWith--用于指定junit运行环境,是junit提供给其他框架测试环境接口扩展,为了便于使用spring的依赖注入,spring提供了org.springframework.test.context.junit4.SpringJUnit4ClassRunner作为Junit测试环境。

   @ContestConfiguration--用于加载spring的配置文件,“classpath:”是固定的,xxxxx.xml是配置文件的名称

   @WebAppConfiguration

1、@WebAppConfiguration注解在此类上,用来声明加载的ApplicationContex是一个WebApplicationContext。它的属性指定的是Web资源的位置,默认为src/main/webapp。

2、MockMvc-模拟MVC对象,通过MockMvcBuilders.webAppContextSetup(this.wac).build()初始化

3、可以在测试用例中注入Spring的Bean

4、可注入WebApplicationConext

5、可注入模拟的http session

6、可注入模拟的http request

7、@Before在测试开始之前进行的初始化工作

8、模拟向/normal进行get请求

9、预期控制返回状态为200

10、预期view的名称为page

原文地址:https://www.cnblogs.com/yourGod/p/9116929.html