SpringMvc基础(六):SpringMvc的测试

(1)概念

测试很重要,大家都知道。前面也讲过不启动项目就可以进行的简单测试的方法。这里主要进行和SpringMvc相关的测试,主要涉及控制器的测试。

有人会有疑问,起项目然后点点测试不是一样嘛,又不是特别麻烦。这涉及到一个概念:测试驱动开发

测试驱动开发:设计人员按照需求先写一个自己预期结果的测试用例,不断地编码和重构,让测试用例通过,这样才能保证软件的质量和可控性

(2)使用

==>使用@WebAppConfiguration指定加载的ApplicationContext是一个WebApplicationContext

==>借助Junit演示对普通页面转向的控制器的测试

==>借助Spring TestContext framework演示对RestController的测试

(3)示例

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.wisely</groupId>
  <artifactId>hightlight_springmvc7</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>hightlight_springmvc7 Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
     <dependency>
    	<groupId>javax</groupId>
    	<artifactId>javaee-web-api</artifactId>
    	<version>7.0</version>
    	<scope>provided</scope>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-webmvc</artifactId>
    	<version>4.1.5.RELEASE</version>
    </dependency>
    <dependency>
    	<groupId>javax.servlet</groupId>
    	<artifactId>jstl</artifactId>
    	<version>1.2</version>
    </dependency>
    <dependency>
    	<groupId>javax.servlet</groupId>
    	<artifactId>javax.servlet-api</artifactId>
    	<version>3.1.0</version>
    	<scope>provided</scope>
    </dependency>
    <dependency>
    	<groupId>javax.servlet.jsp</groupId>
    	<artifactId>jsp-api</artifactId>
    	<version>2.2</version>
    	<scope>provided</scope>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-tx</artifactId>
    	<version>4.1.5.RELEASE</version>
    </dependency>
    <dependency>
    	<groupId>org.slf4j</groupId>
    	<artifactId>slf4j-api</artifactId>
    	<version>1.7.5</version>
    </dependency>
    <dependency>
    	<groupId>log4j</groupId>
    	<artifactId>log4j</artifactId>
    	<version>1.2.16</version>
    </dependency>
    <dependency>
    	<groupId>org.slf4j</groupId>
    	<artifactId>jcl-over-slf4j</artifactId>
    	<version>1.7.5</version>
    </dependency>
    <dependency>
    	<groupId>ch.qos.logback</groupId>
    	<artifactId>logback-classic</artifactId>
    	<version>1.0.13</version>
    </dependency>
    <dependency>
    	<groupId>ch.qos.logback</groupId>
    	<artifactId>logback-core</artifactId>
    	<version>1.0.13</version>
    </dependency>
    <dependency>
    	<groupId>ch.qos.logback</groupId>
    	<artifactId>logback-access</artifactId>
    	<version>1.0.13</version>
    </dependency>
    <dependency>
    	<groupId>com.fasterxml.jackson.core</groupId>
    	<artifactId>jackson-databind</artifactId>
    	<version>2.5.3</version>
    </dependency>
    <dependency>
    	<groupId>com.fasterxml.jackson.dataformat</groupId>
    	<artifactId>jackson-dataformat-xml</artifactId>
    	<version>2.5.3</version>
    </dependency>
    <dependency>
    	<groupId>commons-fileupload</groupId>
    	<artifactId>commons-fileupload</artifactId>
    	<version>1.3.1</version>
    </dependency>
    <dependency>
    	<groupId>commons-io</groupId>
    	<artifactId>commons-io</artifactId>
    	<version>2.3</version>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-test</artifactId>
    	<version>4.1.5.RELEASE</version>
    	<scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>hightlight_springmvc7</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
         <plugin>
        	<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>2.3.2</version>
			<configuration>
				<source>${java.version}</source>
				<target>${java.version}</target>
			</configuration>
        </plugin>
        <plugin>
        	<groupId>org.apache.maven.plugins</groupId>
        	<artifactId>maven-war-plugin</artifactId>
        	<version>2.3</version>
        	<configuration>
        		<failOnMissingWebXml>false</failOnMissingWebXml>
        	</configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>
package com.wisely.highlight_springmvc7.service;

import org.springframework.stereotype.Service;

@Service
public class DemoService {

	public String saySomething(){
		return "hello";
	}
}
package com.wisely.highlight_springmvc7.web.chi4_6;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.wisely.highlight_springmvc7.MyMvcConfig;
import com.wisely.highlight_springmvc7.service.DemoService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { MyMvcConfig.class })
@WebAppConfiguration("src/main/resources")
public class TestControllerIntegrationTests {
	private MockMvc MockMvc;// 模拟MVC对象

	@Autowired
	private DemoService demoService;

	@Autowired
	WebApplicationContext wac;

	@Autowired
	MockHttpSession session;// 模拟session

	@Autowired
	MockHttpServletRequest request;// 模拟request

	@Before
	// 测试开始前的初始化
	// 声明加载的ApplicationContext是WebApplicationContext
	public void setup() {
		this.MockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
	}

	@Test
	public void testNormalController() throws Exception {
		MockMvc.perform(get("/normal"))
				.andExpect(status().isOk())
				.andExpect(view().name("page"))
				.andExpect(forwardedUrl("/WEB-INF/classes/views/page.jsp"))
				.andExpect(model().attribute("msg", demoService.saySomething()));
	}

	@Test
	public void testRestController() throws Exception {
		MockMvc.perform(get("/testRest")).andExpect(status().isOk())
				.andExpect(content().contentType("text/plain;charset=UTF-8"))
				.andExpect(content().string(demoService.saySomething()));
	}

}
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>@ControllerAdvice Demo</title>
</head>
<body>

<div>
Welcome to Spring Mvc 
</div>
</body>
</html>
package com.wisely.highlight_springmvc7.web.chi4_6;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wisely.highlight_springmvc7.service.DemoService;

@Controller
public class NormalController {

	@Autowired
	public DemoService demoService;
	
	@RequestMapping("/normal")
	public String testPage(Model model){
		model.addAttribute("msg",demoService.saySomething());
		return "page";
	}
}
package com.wisely.highlight_springmvc7.web.chi4_6;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.wisely.highlight_springmvc7.service.DemoService;

@RestController
public class MyRestController {

	@Autowired
	DemoService demoService;
	
	@RequestMapping(value="/testRest",produces="text/plain;charset=UTF-8")
	public @ResponseBody String testRest(){
		return demoService.saySomething();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 下面是一个简单的Spring MVC测试用例: ``` @RunWith(SpringRunner.class) @WebMvcTest(MyController.class) public class MyControllerTest { @Autowired private MockMvc mockMvc; @Test public void testHello() throws Exception { mockMvc.perform(get("/hello")) .andExpect(status().isOk()) .andExpect(content().string("Hello World!")); } } ``` 在这个测试用例中,我们使用了`@RunWith(SpringRunner.class)`注解来启动Spring容器,并使用`@WebMvcTest(MyController.class)`注解来指定要测试的控制器类。 在`MyControllerTest`类中,我们注入了`MockMvc`对象,这个对象可以模拟HTTP请求和响应,从而进行控制器的测试。 在`testHello`方法中,我们使用了`mockMvc.perform(get("/hello"))`来模拟GET请求,并使用`andExpect`断言来验证请求的状态码和响应内容。 以上就是一个简单的Spring MVC测试用例示例。 ### 回答2: Spring MVC 测试用例是用来验证 Spring MVC 控制器的正确性和稳定性的。通过编写测试用例,可以对控制器的各个方法进行单元测试,以确保其输出符合预期。以下是编写 Spring MVC 测试用例的步骤: 1. 配置测试环境:在测试类中使用 @RunWith(SpringJUnit4ClassRunner.class) 注解来指定测试运行器为 SpringJUnit4ClassRunner,使测试能够在 Spring 环境中运行。 2. 创建 MockMvc 实例:通过使用 MockMvcBuilders.standaloneSetup(controller) 方法,创建一个 MockMvc 实例来模拟 Spring 容器和 HTTP 请求。 3. 编写测试方法:可以编写多个测试方法来测试控制器的不同功能。对于每个测试方法,可以通过 MockMvc 的 perform() 方法发送相应的 HTTP 请求,并使用 andExpect() 方法设置对响应的期望结果。 4. 断言结果:使用 org.springframework.test.util.AssertionErrors 类中的 assertFalse()、assertTrue()、assertEquals() 等方法来对响应结果进行断言,验证控制器的输出是否与预期结果一致。 5. 运行测试:在测试类中,运行所有编写的测试方法,可以通过在测试类或测试方法上使用 @Test 注解来标记需要运行测试方法。 编写测试用例的目的是为了保证控制器的正确性和稳定性。通过覆盖各种情况的测试用例,可以及时发现并修复控制器中的潜在问题,从而提高系统的健壮性和可靠性。同时,测试用例也是开发人员在迭代开发过程中确保代码修改没有引入新问题的重要手段。 ### 回答3: Spring MVC是一个用于构建Web应用程序的Java框架。它采用MVC(模型-视图-控制器)架构模式来分离应用程序的关注点,使开发更加模块化和可维护。 在编写Spring MVC应用程序时,测试是不可或缺的一部分。测试用例是为了验证应用程序的正确性,并在进行任何更改或扩展之前提供反馈。 基本的Spring MVC测试用例包括以下几个方面: 1. 控制器测试:编写测试用例来验证控制器的行为和功能。这可能涉及到模拟请求和断言响应结果是否符合预期。可以使用MockMvc或Mockito等工具来模拟请求。 2. 集成测试:在整个应用程序的各个层级进行测试,以确保各个组件之间的协作正常工作。这可能涉及到模拟数据库或其他外部依赖,并验证整个请求-响应过程是否正常。 3. 表单验证测试:对于包含表单的页面,编写测试用例来确保表单验证功能正常工作。可以模拟输入数据并验证验证器是否按预期方式处理输入。 4. 异常处理测试:编写测试用例来验证应用程序在发生异常时的行为。可以模拟抛出异常的场景并断言应用程序是否恰当地处理了异常。 5. 页面渲染测试:编写测试用例来验证视图的正确渲染。这包括验证响应中的HTML标签、CSS样式和脚本等。 6. REST API测试:如果应用程序提供RESTful API,编写测试用例来验证API的正确性。可以模拟HTTP请求,并验证相应的JSON或XML是否符合预期。 总之,Spring MVC测试用例是确保应用程序正常运行的关键组成部分。通过编写全面的测试用例,可以更好地保证应用程序的质量和稳定性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鹏哥哥啊Aaaa

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值