对于web项目如果希望通过url来进行单元测试,但是启动服务器和建立http client 来进行测试非常麻烦,并且依赖网络环境。这样我们可以通过引入MockMvc进行测试。

一、引入jar包 

        <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path-assert</artifactId>
<version>0.8.1</version>
</dependency>

二、测试代码

  1、dao层和service层

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
@TransactionConfiguration(transactionManager="txManager",defaultRollback=true)
@Transactional//应用事务,这样测试就不会在数据库中留下痕迹
public class BaseJunit4Test { 
  @Test
  public void test(){
  }
}
public class LoginServiceTest extends BaseJunit4Test{

    @Autowired
private LoginService loginService; @Test
public void testLogin() {
String account = "kyle";
String password = "123456";
String result = loginService.Login(account, password);
assertEquals("登陆成功",result);
} }
public class LoginMapperTest extends BaseJunit4Test{

    @Autowired
private LoginMapper loginMapper; @Test
public void testGetUserPwdByAccount() {
String account = "kyle";
String pwd = loginMapper.getUserPwdByAccount(account);
assertEquals("123456",pwd);
} }

  2、web层测试

@RunWith(SpringJUnit4ClassRunner.class)//使用Spring Test组件进行单元测试
@ContextConfiguration(locations={"classpath:applicationContext.xml",//加载配置文件
"classpath:spring-mvc.xml"
})
@WebAppConfiguration
@TransactionConfiguration(transactionManager="txManager",defaultRollback=true)
@Transactional//应用事务,这样测试就不会在数据库中留下痕迹
public class BaseWebJunit4Test {

    protected MockMvc mockMvc;
protected MockHttpSession mockHttpSession; @Autowired
protected WebApplicationContext context; @Before
public void initMockMvc() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
this.mockHttpSession = new MockHttpSession();
mockMvc.perform(MockMvcRequestBuilders.post("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("account", "kyle")
.param("password", "123456")
.session(mockHttpSession))
.andExpect(status().isOk())
.andExpect(content().string("登陆成功"))
.andDo(print())
.andReturn().getResponse().getContentAsString();
} @Test
public void test(){ } }
public class LoginControllerTest extends BaseWebJunit4Test{

    @Test
public void testLogin() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("account", "kyle")
.param("password", "123456")
.session(mockHttpSession))
.andExpect(status().isOk())
.andExpect(content().string("登陆成功"))
.andDo(print())
.andReturn().getResponse().getContentAsString();
} @Test
public void testGetUserInfo() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/getUserInfo")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"account\":\"kyle\"}")
.session(mockHttpSession))
.andExpect(status().isOk())
.andExpect(jsonPath("$.password", is("123456")))
.andDo(print())
.andReturn().getResponse().getContentAsString(); } }

三、mock mvc 相关api

  https://blog.csdn.net/xiao_xuwen/article/details/52890730

springmvc 项目单元测试的更多相关文章

  1. springmvc 项目完整示例02 项目创建-eclipse创建动态web项目 配置文件 junit单元测试

    包结构 所需要的jar包直接拷贝到lib目录下 然后选定 build path 之后开始写项目代码 配置文件 ApplicationContext.xml <?xml version=" ...

  2. springmvc 项目完整示例06 日志–log4j 参数详细解析 log4j如何配置

    Log4j由三个重要的组件构成: 日志信息的优先级 日志信息的输出目的地 日志信息的输出格式 日志信息的优先级从高到低有ERROR.WARN. INFO.DEBUG,分别用来指定这条日志信息的重要程度 ...

  3. springmvc 项目完整示例01 需求与数据库表设计 简单的springmvc应用实例 web项目

    一个简单的用户登录系统 用户有账号密码,登录ip,登录时间 打开登录页面,输入用户名密码 登录日志,可以记录登陆的时间,登陆的ip 成功登陆了的话,就更新用户的最后登入时间和ip,同时记录一条登录记录 ...

  4. springmvc 项目完整示例03 小结

    利用spring 创建一个web项目 大致原理 利用spring的ioc 原理,例子中也就是体现在了配置文件中 设置了自动扫描注解 配置了数据库信息等 一般一个项目,主要有domain,dao,ser ...

  5. springmvc 项目完整示例04 整合mybatis mybatis所需要的jar包 mybatis配置文件 sql语句 mybatis应用

    百度百科: MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBat ...

  6. springmvc 项目完整示例05 日志 --log4j整合 配置 log4j属性设置 log4j 配置文件 log4j应用

    log4j 就是log for java嘛,老外都喜欢这样子,比如那个I18n  ---internationalization  不就是i和n之间有18个字母... http://logging.a ...

  7. springmvc 项目完整示例07 设置配置整合springmvc springmvc所需jar包springmvc web.xml文件配置

    前面主要是后台代码,spring以及mybatis的整合 下面主要是springmvc用来处理请求转发,展现层的处理 之前所有做到的,完成了后台,业务层和持久层的开发完成了 接下来就是展现层了 有很多 ...

  8. springmvc 项目完整示例08 前台页面以及知识点总结

    至此已经基本测试成功了,我们稍作完善,让它成为一个更加完整的项目 我们现在重新规划下逻辑 两个页面 一个登录页面 一个欢迎页面 登陆页面输入账号密码,登陆成功的话,跳转登陆成功 欢迎页面 并且,更新用 ...

  9. 零配置简单搭建SpringMVC 项目

    SpringMVC是比较常用的JavaWeb框架,非常轻便强悍,能简化Web开发,大大提高开发效率,在各种Web程序中广泛应用.本文采用Java Config的方式搭建SpringMVC项目,并对Sp ...

随机推荐

  1. 列表、enumerate()函数,以及查看数据类型所有的内置方法

    随便看看 """ forList(): 测试list和enumerate()函数 examineFun(): 查看数据类型所有的内置方法 ""&quo ...

  2. LeetCode算法题-Kth Largest Element in a Stream(Java实现)

    这是悦乐书的第296次更新,第315篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第164题(顺位题号是703).设计一个类来查找流中第k个最大元素.请注意,它是排序顺序 ...

  3. LeetCode算法题-Convert BST to Greater Tree(Java实现)

    这是悦乐书的第255次更新,第268篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第122题(顺位题号是538).给定二进制搜索树(BST),将其转换为更大树,使原始BS ...

  4. 阿里巴巴开源的Asynchronous I/O Design and Implementation

    Motivation I/O access, for the most case, is a time-consuming process, making the TPS for single ope ...

  5. KafkaManager编译安装使用(支持kerberos认证)

    为了能够方便的查看及管理Kafka集群,yahoo提供了一个基于Web的管理工具(Kafka-Manager). 这个工具可以方便的查看集群中Kafka的Topic的状态(分区.副本及消息量等),支持 ...

  6. Example of DenseCRF with non-RGB data

    本笔记本通过一个示例说明如何在非rgb数据上使用DenseCRFs.同时,它将解释基本概念并通过一个示例进行演示,因此即使您正在处理RGB数据,它也可能是有用的,不过也请查看PyDenseCRF's ...

  7. (十五)The Search API

    Now let’s start with some simple searches. There are two basic ways to run searches: one is by sendi ...

  8. springboot在eclipse中运行使用开发配置,打包后运行使用生产环境默认配置

    java命令运行springboot jar文件,指定配置文件可使用如下两个参数中其中一个 --spring.config.location=配置文件路径 -Dspring.profiles.acti ...

  9. linux sort排序及取前几条数据

    查看sort --help -n 根据字符串的数值进行比较 -k 根据某一个关键字的位置或者类型排序 -r 倒序排序 -t 字段分隔,后面跟分隔符 查看head --help -n 打印前几行记录,后 ...

  10. MATLAB accumarray

    先看看subs和val的具体内容 subs = [1 1 1; 2 1 2; 2 3 2; 2 1 2; 2 3 2]; subs = 1     1     1 2     1     2 2    ...