前言:搭建一个简易的环境来练习MVC测试

1.mvc测试环境搭建

目录结构


pom.xml

创建一个SpringBoot的maven工程,导入以下依赖

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.1.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.nateshao</groupId><artifactId>mockito</artifactId><version>0.0.1-SNAPSHOT</version><name>mockito</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version><powermock.version>1.6.1</powermock.version><mock.version>2.8.55</mock.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency><dependency><groupId>org.powermock</groupId><artifactId>powermock-module-junit4</artifactId><version>2.0.7</version><scope>test</scope></dependency><dependency><groupId>org.powermock</groupId><artifactId>powermock-api-mockito2</artifactId><version>2.0.7</version><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.1</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.45</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

sql脚本

CREATE TABLE tb_student (`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'id',`name` VARCHAR(50) NOT NULL DEFAULT '' COMMENT 'name',`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'createTime',`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'updateTime',PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT 'student_entity';

applocation.yml

spring:profiles:active: local

application-local.yml

server:port: 10086spring:datasource:url: jdbc:mysql://localhost:3306/learn?useUnicode=true&characterEncoding=UTF-8&useSSL=false&zeroDateTimeBehavior=convertToNulldriver-class-name: com.mysql.jdbc.Driverusername: rootpassword: rootinitialization-mode: EMBEDDEDinitialSize: 1minIdle: 1maxActive: 2maxWait: 60000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: truetestOnReturn: truemybatis:mapper-locations: classpath:mybatis/*.xml

StudentController.java

package com.atomintl.exchange.learn.controller;import com.atomintl.exchange.learn.common.RestfulPath;
import com.atomintl.exchange.learn.entity.StudentEntity;
import com.atomintl.exchange.learn.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;import java.util.List;@Slf4j
@RestController
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public class StudentController {@Autowiredprivate StudentService studentService;@GetMapping(value = RestfulPath.getStudents)public List<StudentEntity> getStudents(StudentEntity req) {return studentService.findList(req);}@PostMapping(value = RestfulPath.postStudent, consumes = MediaType.APPLICATION_JSON_VALUE)public StudentEntity create(@RequestBody StudentEntity req) {return studentService.insert(req);}@PutMapping(value = RestfulPath.putStudent, consumes = MediaType.APPLICATION_JSON_VALUE)public StudentEntity update(@RequestBody StudentEntity req) {return studentService.update(req);}@DeleteMapping(value = RestfulPath.deleteStudent)public StudentEntity delete(@PathVariable("id") long id) {return studentService.delete(id);}
}

RestfulPath.java

public class RestfulPath {/*** ----- product ----**/public final static String getStudents = "/v1/learn/students";public final static String putStudent = "/v1/learn/student";public final static String postStudent = "/v1/learn/student";public final static String deleteStudent = "/v1/learn/student/{id}";
}

StudentService.java

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import com.atomintl.exchange.learn.entity.StudentEntity;
import com.atomintl.exchange.learn.dao.StudentEntityDao;@Service
public class StudentService {@Resourceprivate StudentEntityDao studentEntityDao;public StudentEntity insert(StudentEntity entity){studentEntityDao.insert(entity);return this.findOne(entity);}public int insertList(List< StudentEntity> entities){return studentEntityDao.insertList(entities);}public List<StudentEntity> findList(StudentEntity entity){return studentEntityDao.findList(entity);}public StudentEntity findOne(StudentEntity entity){return studentEntityDao.findOne(entity);}public StudentEntity update(StudentEntity entity){studentEntityDao.update(entity);return this.findOne(entity);}public StudentEntity delete(long id){StudentEntity entity = new StudentEntity();entity.setId(id);StudentEntity one = studentEntityDao.findOne(entity);studentEntityDao.delete(id);return one;}
}

StudentDao.java

package com.atomintl.exchange.learn.dao;import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import com.atomintl.exchange.learn.entity.StudentEntity;@Mapper
public interface StudentEntityDao {int insert(@Param("pojo") StudentEntity pojo);int insertList(@Param("pojos") List< StudentEntity> pojo);List<StudentEntity> findList(@Param("pojo") StudentEntity pojo);StudentEntity findOne(@Param("pojo") StudentEntity pojo);int update(@Param("pojo") StudentEntity pojo);int delete(@Param("id") long id);
}

StudentEntity.java

package com.atomintl.exchange.learn.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;import java.sql.Timestamp;@Getter
@Setter
@ToString
public class StudentEntity {private Long id;private String name;private Timestamp createTime;private Timestamp updateTime;
}

ScoreService.java

package com.atomintl.exchange.learn.service;import java.math.BigDecimal;/*** 此类用到了单例模式--饿汉式*/
public class ScoreService {private BigDecimal score;private static final ScoreService INSTANCE = new ScoreService();private ScoreService(){}public static ScoreService getInstance() {return INSTANCE;}public BigDecimal addScore(BigDecimal score) {return this.score.add(score);}public BigDecimal getScore() {return this.score;}}

Application.java

package com.atomintl.exchange.learn;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@MapperScan("com.atomintl.exchange.learn.dao")
@SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}

StudentEntityDao.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.atomintl.exchange.learn.dao.StudentEntityDao"><!--auto generated Code--><resultMap id="AllColumnMap" type="com.atomintl.exchange.learn.entity.StudentEntity"><result column="id" property="id"/><result column="name" property="name"/><result column="create_time" property="createTime"/><result column="update_time" property="updateTime"/></resultMap><!--auto generated Code--><sql id="all_column">id,name,create_time,update_time</sql><!--auto generated Code--><insert id="insert">INSERT INTO tb_student<trim prefix="(" suffix=")" suffixOverrides=","><if test="pojo.id != null"> id, </if><if test="pojo.name != null"> name, </if><if test="pojo.createTime != null"> create_time, </if><if test="pojo.updateTime != null"> update_time, </if></trim>VALUES<trim prefix="(" suffix=")" suffixOverrides=","><if test="pojo.id != null"> #{pojo.id}, </if><if test="pojo.name != null"> #{pojo.name}, </if><if test="pojo.createTime != null"> #{pojo.createTime}, </if><if test="pojo.updateTime != null"> #{pojo.updateTime}, </if></trim></insert><!--auto generated Code--><insert id="insertList">INSERT INTO tb_student(<include refid="all_column"/>)VALUES<foreach collection="pojos" item="pojo" index="index" separator=",">(#{pojo.id},#{pojo.name},#{pojo.createTime},#{pojo.updateTime})</foreach></insert><!--auto generated Code--><update id="update">UPDATE tb_student<set><if test="pojo.name != null"> name = #{pojo.name}, </if><if test="pojo.createTime != null"> create_time = #{pojo.createTime}, </if></set>WHERE id = #{pojo.id}</update><!--auto generated Code--><select id="findList" resultMap="AllColumnMap">SELECT<include refid="all_column"/>FROM tb_student<where><if test="pojo.id != null"> AND id = #{pojo.id} </if><if test="pojo.name != null"> AND name = #{pojo.name} </if></where>LIMIT 1000 </select><select id="findOne" resultMap="AllColumnMap">SELECT <include refid="all_column"/>FROM tb_student<where><if test="pojo.id != null"> AND id = #{pojo.id} </if><if test="pojo.name != null"> AND name = #{pojo.name} </if></where>LIMIT 1</select><!--auto generated Code--><delete id="delete">DELETE FROM tb_student where id = #{id}</delete>
</mapper>

到这里基本的环境搭建好了,下面可以开始编写测试用例了

2.测试用例

测试用例目录结构

ObjectFactoryUtil.java

package com.atomintl.exchange.learn.util;import com.atomintl.exchange.learn.entity.StudentEntity;import java.sql.Timestamp;
import java.util.Date;/*** @Author 徐志* @date 2020/7/17 10:07**/
public class ObjectFactoryUtil {/*** 获取一个随机数* @return*/public static Long getRandomNumber(){int root = (int) Math.pow(10, 10);long id;do {long tmp = Math.abs(Double.doubleToLongBits(Math.random()));id = tmp % root;} while (id < (root / 10));return id;}/*** 获取StudentEntity实体对象* @return*/public static StudentEntity getStudentEntity(){StudentEntity entity = new StudentEntity();entity.setId(getRandomNumber());  //将随机数设置为identity.setName("xuzhi"); //设置名字entity.setCreateTime(new Timestamp(new Date().getTime())); //设置创建时期entity.setUpdateTime(new Timestamp(new Date().getTime())); //设置更新时期return entity;}
}

StudentEntityDaoTest.java

package com.atomintl.exchange.learn.dao;import com.atomintl.exchange.learn.entity.StudentEntity;
import com.atomintl.exchange.learn.util.ObjectFactoryUtil;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;import java.util.ArrayList;
import java.util.List;import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;/*** 访问数据库* SpringBoot中的单元测试, @Transactional会回滚数据,保证用例正常执行。* 比如说,进行插入操作,如果没有@Transactional,那么我们每次都要修改插入元素的主键*/
@SpringBootTest
public class StudentEntityDaoTest {@Autowiredprivate StudentEntityDao studentEntityDao;@Test@Transactionalvoid insertTest() {StudentEntity entity = ObjectFactoryUtil.getStudentEntity();studentEntityDao.insert(entity);StudentEntity result = studentEntityDao.findOne(entity);assertThat(result.getId()).isEqualTo(entity.getId());assertThat(result.getName()).isEqualTo(entity.getName());//注意:TimeStamp是有一个时间戳的,所以不能直接进行比较,取一个范围即可assertTrue((entity.getCreateTime().compareTo(result.getCreateTime())<2));assertTrue((entity.getUpdateTime().compareTo(result.getUpdateTime())<2));/*错误的写法assertThat(result.getCreateTime()).isEqualTo(entity.getCreateTime());assertThat(result.getUpdateTime()).isEqualTo(entity.getUpdateTime());*/}@Test@Transactionalpublic void insertListTest() {List<StudentEntity> list=new ArrayList<>();StudentEntity entity1 = ObjectFactoryUtil.getStudentEntity();StudentEntity entity2 = ObjectFactoryUtil.getStudentEntity();StudentEntity entity3 = ObjectFactoryUtil.getStudentEntity();list.add(entity1);list.add(entity2);list.add(entity3);int i = studentEntityDao.insertList(list);Assert.assertEquals(3,i);}@Test@Transactionalvoid findListTest() {//注意,对集合进行测试时,只需要对返回集合中元素的个数进行断言,以及其中的某一个元素进行断言即可,//不需要完全比较集合当中所有的元素//先插入,再查找StudentEntity entity = ObjectFactoryUtil.getStudentEntity();List<StudentEntity> list=new ArrayList<>();list.add(entity);int i = studentEntityDao.insertList(list);Assert.assertEquals(1,i);List<StudentEntity> entities = studentEntityDao.findList(entity);assertThat(list.get(0).getId()).isEqualTo(entities.get(0).getId());assertThat(list.get(0).getName()).isEqualTo(entities.get(0).getName());//注意:TimeStamp是有一个时间戳的,所以不能直接进行比较,取一个范围即可assertTrue((list.get(0).getCreateTime().compareTo(entities.get(0).getCreateTime())<2));assertTrue((list.get(0).getUpdateTime().compareTo(entities.get(0).getUpdateTime())<2));/*错误写法assertThat(list.get(0).getCreateTime()).isEqualTo(entities.get(0).getCreateTime());assertThat(list.get(0).getUpdateTime()).isEqualTo(entities.get(0).getUpdateTime());*/}@Test@Transactionalpublic void findOneTest() {StudentEntity entity = ObjectFactoryUtil.getStudentEntity();studentEntityDao.insert(entity);StudentEntity one = studentEntityDao.findOne(entity);assertThat(one.getId()).isEqualTo(entity.getId());assertThat(one.getName()).isEqualTo(entity.getName());//注意:TimeStamp是有一个时间戳的,所以不能直接进行比较,取一个范围即可assertTrue((one.getCreateTime().compareTo(entity.getCreateTime())<2));assertTrue((one.getUpdateTime().compareTo(entity.getUpdateTime())<2));}@Test@Transactionalpublic void updateTest() {//先插入,再修改,确保有这条数据StudentEntity entity = ObjectFactoryUtil.getStudentEntity();studentEntityDao.insert(entity);//修改entity.setName("xiongda");int update = studentEntityDao.update(entity);Assert.assertEquals(1,update);}@Test@Transactionalpublic void deleteTest() {//先插入,再删除,确保有这条数据StudentEntity entity = ObjectFactoryUtil.getStudentEntity();studentEntityDao.insert(entity);int delete = studentEntityDao.delete(entity.getId());assertThat(delete).isEqualTo(1);}
}

StudentServiceTest.java

package com.atomintl.exchange.learn.service;import com.atomintl.exchange.learn.dao.StudentEntityDao;
import com.atomintl.exchange.learn.entity.StudentEntity;
import com.atomintl.exchange.learn.util.ObjectFactoryUtil;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;import java.util.ArrayList;
import java.util.List;import static org.assertj.core.api.Assertions.assertThat;/*** 使用powermock测试StudentService。没有访问数据库*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({StudentEntityDao.class,StudentService.class})
public class StudentServiceTest {@InjectMocksprivate StudentService studentService;@Mockprivate StudentEntityDao studentEntityDao;@Testpublic void insertTest() {//1.准备数据StudentEntity entity = ObjectFactoryUtil.getStudentEntity();//2.涂鸦操作//注意点:我们studentEntityDao.insert方法里面用到了findOne方法,所以得when一下PowerMockito.when(studentEntityDao.insert(entity)).thenReturn(1);PowerMockito.when(studentEntityDao.findOne(entity)).thenReturn(entity);//3.mock对象执行方法StudentEntity insert = studentService.insert(entity);//4.断言,将插入的entity和数据库中查询到的entity进行比较assertThat(insert.getId()).isEqualTo(entity.getId());assertThat(insert.getName()).isEqualTo(entity.getName());assertThat(insert.getCreateTime()).isEqualTo(entity.getCreateTime());assertThat(insert.getUpdateTime()).isEqualTo(entity.getUpdateTime());}@Testpublic void insertListTest() {//1.准备数据List<StudentEntity> list=new ArrayList<>();StudentEntity entity1 = ObjectFactoryUtil.getStudentEntity();StudentEntity entity2=ObjectFactoryUtil.getStudentEntity();StudentEntity entity3=ObjectFactoryUtil.getStudentEntity();list.add(entity1);list.add(entity2);list.add(entity3);//2.涂鸦操作PowerMockito.when(studentEntityDao.insertList(list)).thenReturn(3);//3.Mock对象执行方法int count = studentEntityDao.insertList(list);//4.断言Assert.assertEquals(3,count);}@Testpublic void findListTest() {//1.准备数据StudentEntity entity = ObjectFactoryUtil.getStudentEntity();//2.涂鸦操作List<StudentEntity> list=new ArrayList<StudentEntity>();list.add(entity);PowerMockito.when(studentEntityDao.findList(entity)).thenReturn(list);//3.执行Mock对象的操作List<StudentEntity> result = studentEntityDao.findList(entity);//4.断言比较Assert.assertEquals(result,list);}@Testpublic void findOneTest() {//1.准备数据StudentEntity entity = ObjectFactoryUtil.getStudentEntity();//2.涂鸦操作PowerMockito.when(studentEntityDao.findOne(entity)).thenReturn(entity);//3.执行语句StudentEntity one = studentEntityDao.findOne(entity);//4.断言Assert.assertEquals(entity.getId(),one.getId());Assert.assertEquals(entity.getName(),one.getName());Assert.assertEquals(entity.getCreateTime(),one.getCreateTime());Assert.assertEquals(entity.getUpdateTime(),one.getUpdateTime());}@Testpublic void updateTest() {StudentEntity entity = ObjectFactoryUtil.getStudentEntity();//注意点:我们studentEntityDao.update方法里面用到了findOne方法,所以得when一下PowerMockito.when(studentEntityDao.update(entity)).thenReturn(1);PowerMockito.when(studentEntityDao.findOne(entity)).thenReturn(entity);StudentEntity update = studentService.update(entity);//将插入的entity和数据库中查询到的entity进行比较assertThat(update.getId()).isEqualTo(entity.getId());assertThat(update.getName()).isEqualTo(entity.getName());assertThat(update.getCreateTime()).isEqualTo(entity.getCreateTime());assertThat(update.getUpdateTime()).isEqualTo(entity.getUpdateTime());}@Testpublic void deleteTest() {Long id = ObjectFactoryUtil.getRandomNumber();/* StudentEntity entity = ObjectFactoryUtil.getStudentEntity();entity.setId(id);*/StudentEntity entity = PowerMockito.mock(StudentEntity.class);try {PowerMockito.whenNew(StudentEntity.class).withNoArguments().thenReturn(entity);} catch (Exception e) {e.printStackTrace();}//注意点:我们studentEntityDao.update方法里面用到了findOne方法,所以得when一下PowerMockito.when(studentEntityDao.delete(id)).thenReturn(1);PowerMockito.when(studentEntityDao.findOne(entity)).thenReturn(entity);StudentEntity delete = studentService.delete(id);//将插入的entity和数据库中查询到的entity进行比较assertThat(delete.getId()).isEqualTo(entity.getId());assertThat(delete.getName()).isEqualTo(entity.getName());assertThat(delete.getCreateTime()).isEqualTo(entity.getCreateTime());assertThat(delete.getUpdateTime()).isEqualTo(entity.getUpdateTime());}
}

ScoreServiceTest.java

package com.atomintl.exchange.learn.service;import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;import java.math.BigDecimal;import static org.junit.jupiter.api.Assertions.*;/*** 使用powermock测试ScoreService*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({ScoreService.class})
public class ScoreServiceTest {/*//方式一:使用注解@Mockprivate ScoreService scoreService;*/@Testpublic void addScore() {//方式二:使用mock方法来创建一个ScoreService的对象ScoreService scoreService = PowerMockito.mock(ScoreService.class);//因为我们需要用到getInstance()方法,这是一个静态方法,所以要用到mockStaticPowerMockito.mockStatic(ScoreService.class);//这里需要返回一个ScoreService对象,我们可以通过方式一和方式二两种方式来获得这个对象PowerMockito.when(ScoreService.getInstance()).thenReturn(scoreService);PowerMockito.when(scoreService.addScore(new BigDecimal(100))).thenReturn(BigDecimal.valueOf(100));BigDecimal score = scoreService.addScore(new BigDecimal(100));assertEquals(BigDecimal.valueOf(100),score);}@Testpublic void getScore() {//方式二,创建一个mock对象ScoreService scoreService = PowerMockito.mock(ScoreService.class);//因为我们需要用到getInstance()方法,这是一个静态方法,所以要用到mockStaticPowerMockito.mockStatic(ScoreService.class);//这里需要返回一个ScoreService对象,我们可以通过方式一和方式二两种方式来获得PowerMockito.when(ScoreService.getInstance()).thenReturn(scoreService);PowerMockito.when(scoreService.getScore()).thenReturn(BigDecimal.valueOf(100));assertEquals(BigDecimal.valueOf(100),scoreService.getScore());}
}

StudentControllerTest.java

package com.atomintl.exchange.learn.controller;
import com.atomintl.exchange.learn.Application;
import com.atomintl.exchange.learn.entity.StudentEntity;
import com.atomintl.exchange.learn.service.StudentService;
import com.atomintl.exchange.learn.util.ObjectFactoryUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;import java.util.ArrayList;
import java.util.List;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;/*** 使用Mockmvc测试StudentController,访问数据库*/@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration
//@WebAppConfiguration
@SpringBootTest(classes = Application.class)
public class StudentControllerTest {private MockMvc mockMvc;@Autowiredprivate StudentService studentService;@Autowiredprivate WebApplicationContext webApplicationContext;@Beforepublic void setUp() throws Exception{//初始化mockMVC对象mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();}@Test@Transactionalpublic void getStudentsTest() throws Exception {//先插入,再查询List<StudentEntity> list=new ArrayList<>();StudentEntity entity1 = ObjectFactoryUtil.getStudentEntity();entity1.setId(111111L);StudentEntity entity2 = ObjectFactoryUtil.getStudentEntity();entity2.setId(111112L);StudentEntity entity3 = ObjectFactoryUtil.getStudentEntity();entity3.setId(111113L);list.add(entity1);list.add(entity2);list.add(entity3);studentService.insertList(list);MvcResult authResult = null;//使用get方式来调用接口。authResult = mockMvc.perform(get("/v1/learn/students")//请求参数的类型.contentType(MediaType.APPLICATION_JSON_VALUE)//请求的参数(可多个).param("name","xuzhi")).andExpect(status().isOk()).andReturn();//获取返回值,使用Json数组封装JSONArray jsonArray = new JSONArray(authResult.getResponse().getContentAsString());//比对数组中的第一个值即可JSONObject jsonObject = (JSONObject) jsonArray.get(0);Integer id = (Integer)jsonObject.get("id");String name=(String)jsonObject.get("name");//断言比较Assert.assertEquals("111111",String.valueOf(id));Assert.assertEquals("xuzhi",name);}@Test@Transactionalpublic void createTest() throws Exception {//创建一个实体类,并将实体类转化成为json字符串格式StudentEntity entity = ObjectFactoryUtil.getStudentEntity();ObjectMapper mapper=new ObjectMapper();ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();String pojo = ow.writeValueAsString(entity);MvcResult authResult = null;//使用get方式来调用接口。authResult = mockMvc.perform(post("/v1/learn/student")//请求参数的类型.contentType(MediaType.APPLICATION_JSON_VALUE)//请求的参数(可多个),post请求,参数使用这个.content(pojo)).andExpect(status().isOk()).andReturn();//插入之后findOne一下,看看是否插入成功StudentEntity one = studentService.findOne(entity);Assert.assertEquals(entity.getId(),one.getId());Assert.assertEquals(entity.getName(),one.getName());//获取请求返回值JSONObject jsonObject=new JSONObject(authResult.getResponse().getContentAsString());Integer id = (Integer)jsonObject.get("id");String name = (String)jsonObject.get("name");//断言Assert.assertEquals(entity.getId(),Long.valueOf(id));Assert.assertEquals("xuzhi",name);}@Test@Transactionalpublic void updateTest() throws Exception {//创建一个实体类,先插入StudentEntity entity = ObjectFactoryUtil.getStudentEntity();studentService.insert(entity);//update方法中,需要将实体类转化成为json字符串格式然后传参//将实体类对象修改entity.setName("spiderman");ObjectMapper mapper=new ObjectMapper();ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();String pojo = ow.writeValueAsString(entity);MvcResult authResult = null;//使用put方式来调用接口。authResult = mockMvc.perform(put("/v1/learn/student")//请求参数的类型.contentType(MediaType.APPLICATION_JSON_VALUE)//请求的参数(可多个),post请求,参数使用这个.content(pojo)).andExpect(status().isOk()).andReturn();//插入之后findOne一下,看看是否插入成功StudentEntity one = studentService.findOne(entity);Assert.assertEquals(entity.getId(),one.getId());Assert.assertEquals(entity.getName(),one.getName());//获取请求返回值JSONObject jsonObject=new JSONObject(authResult.getResponse().getContentAsString());Integer id = (Integer)jsonObject.get("id");String name = (String)jsonObject.get("name");//断言Assert.assertEquals(entity.getId(),Long.valueOf(id));Assert.assertEquals("spiderman",name);}@Test@Transactionalpublic void deleteTest() throws Exception {//创建一个实体类,先插入StudentEntity entity = ObjectFactoryUtil.getStudentEntity();studentService.insert(entity);//获取实体类idLong sid= entity.getId();//检测是否插入成功StudentEntity one = studentService.findOne(entity);Assert.assertEquals(entity.getId(),one.getId());Assert.assertEquals(entity.getName(),one.getName());MvcResult authResult = null;//使用delete方式来调用接口。// authResult = mockMvc.perform(delete(RestfulPath.deleteStudent.replaceAll("\\{id\\}",String.valueOf(sid)))authResult = mockMvc.perform(delete("/v1/learn/student/"+sid)//请求参数的类型.contentType(MediaType.APPLICATION_JSON_VALUE)//这里是在路径上进行传参).andExpect(status().isOk()).andReturn();//模拟请求之后findOne一下,看看是否删除成功StudentEntity one2 = studentService.findOne(entity);Assert.assertNull(one2);//获取请求返回值String string = authResult.getResponse().getContentAsString();JSONObject jsonObject=new JSONObject(string);Integer id = (Integer)jsonObject.get("id");String name = (String)jsonObject.get("name");//断言Assert.assertEquals(entity.getId(),Long.valueOf(id));Assert.assertEquals("xuzhi",name);}
}

总结:接触powermock不久,搭建这么一个小demo来帮助自己学习理解,个人感觉powermock还是挺强大的。在做单元测试的时候作用大的很。

PowerMock之MVC测试相关推荐

  1. Spring MVC测试框架

    原文链接:http://jinnianshilongnian.iteye.com/blog/2004660 Spring MVC测试框架详解--服务端测试 博客分类: springmvc杂谈 spri ...

  2. springBoot单元测试-模拟MVC测试

    1)模拟mvc测试,和基础测试是一样的, 都需要在pom文件中引入junit的支持. 略 2)编写测试类 Application1TestMVC 在类头上除啦加入之前的@RunWith(SpringR ...

  3. spring框架mvc框架_Spring的MVC测试框架入门–第1部分

    spring框架mvc框架 最新推出的主要Spring框架是Spring MVC测试框架,Spring Guys声称它是"一流的JUnit支持,可通过流畅的API测试客户端和服务器端Spri ...

  4. spring框架mvc框架_Spring MVC测试框架入门–第2部分

    spring框架mvc框架 这个迷你系列的第一个博客介绍了Spring MVC测试框架,并演示了其在单元测试Spring MVC Controller类中作为控制器而不是POJO进行单元测试的用途. ...

  5. Spring MVC测试框架入门–第1部分

    最新推出的主要Spring框架是Spring MVC测试框架,Spring Guys声称它是"一流的JUnit支持,可通过流畅的API测试客户端和服务器端Spring MVC代码" ...

  6. Spring MVC测试框架入门–第2部分

    这个迷你系列的第一个博客介绍了Spring MVC测试框架,并展示了其在单元测试Spring MVC Controller类中作为控制器而不是POJO进行单元测试的用途. 现在是时候讨论使用框架进行集 ...

  7. 14.6 Spring MVC 测试框架(翻译)

    14.6 Spring MVC 测试框架(每天翻译一点点) Spring MVC测试框架对 Spring MVC 代码提供一流的测试支持 ,它拥有一个 fluent API ,可以和JUnit, Te ...

  8. Spring MVC测试框架详解——服务端测试

    随着RESTful Web Service的流行,测试对外的Service是否满足期望也变的必要的.从Spring 3.2开始Spring了Spring Web测试框架,如果版本低于3.2,请使用sp ...

  9. Java单元测试之模拟利器-使用PowerMock进行Mock测试

    首页 国产Linux Linux命令 openSUSE ArchLinux Slackware FreeBSD Ubuntu CentOS Fedora Debian PHP教程 在线教程 登录 注册 ...

最新文章

  1. AI一分钟 | 娃哈哈要造智能汽车?世界顶级机器学习科学家黄恒加盟京东
  2. 深度图像检测算法总结与对比
  3. cstring越界_try catch 捕捉数组越界异常
  4. Multiple classes found for path in the registry of this declarative base. Please use a fully
  5. 莫名的_locals属性
  6. 知识产权创业的比赛结果
  7. python batchnorm2d_PyTorch中的BatchNorm2d层
  8. 【zookeeper】zookeeper 的监听机制
  9. HttpClient连接池的连接保持、超时和失效机制
  10. Android 四大组件学习之ContentProvider三
  11. 教你在网吧“移”电影
  12. 1024公众号福利放送
  13. h5 字体加粗_html、css文字加粗方法
  14. 服务器没有显示器能接笔记本吗,笔记本能连显示器吗,笔记本怎么才能接显示器(图文)...
  15. apple pay 技术_如何在Apple Watch上设置和使用Apple Pay
  16. 现代编程语言(3):zig
  17. Another app is currently holding the yum lock解决方法
  18. 学计算机网络技术遇到问题,维护计算机网络教室的常见问题及解决方案
  19. ubuntu卡在无限循环登录界面,进不去桌面的问题#不重装是我们最后的倔强!#
  20. windows编写bat脚本删除隐藏文件夹下的所有文件

热门文章

  1. 十八数藏柏松:数字藏品拥有广阔的发展空间,能为社会输出更好的价值
  2. 杭电OJ-ACM1018 (Big Number)
  3. 机器学习笔记---从极大似然估计的角度看待Logistic回归
  4. ros_hostname与ros_ip
  5. android app防止锁屏_设置Android系统永不锁屏永不休眠的方法
  6. 安卓 微信公众号 默认不操作拦截回退失败
  7. 逆向工程实验_lab0(密码学算法逆向)
  8. 一次linux oops分析
  9. android百度地图行政区填充颜色
  10. 做了3年半测试员,薪资不到20K,今天,我辞职了…