测试用例-powermock实践-mock一个mvc框架


mvc开发框架大家再熟悉不过了,那么如何在项目上mock一个mvc呢?

学会了这个,我们也可以给自己代码跑一下单测对吧。

即使上线了,也不用担心,因为有单测在保障我们的代码逻辑

数据库

tb_student

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';

application-local.yml

server:
  port: 10086

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/learn?useUnicode=true&characterEncoding=UTF-8&useSSL=false&zeroDateTimeBehavior=convertToNull
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 123456
    initialization-mode: EMBEDDED
    initialSize: 1
    minIdle: 1
    maxActive: 2
    maxWait: 60000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: true
    testOnReturn: true

mybatis:
  mapper-locations: classpath:mybatis/*.xml

启动类

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);
    }

}

StudentController

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 {

    @Autowired
    private 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);
    }
}

StudentService

package com.atomintl.exchange.learn.service;

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 {

    @Resource
    private 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;
    }
}

ScoreService

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;
    }

}

StudentEntity

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;

}

StudentEntityDao

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);
}

StudentController

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 {

    @Autowired
    private 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

package com.atomintl.exchange.learn.common;

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}";
}

以上,一个mvc框架搭建完毕

mock一个mvc

StudentControllerTest

package com.atomintl.exchange.learn.controller;

import com.atomintl.exchange.learn.Application;
import com.atomintl.exchange.learn.common.RestfulPath;
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.core.JsonProcessingException;
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.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.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;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
@SpringBootTest(classes = Application.class)
public class StudentControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private StudentService studentService;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setUp() throws Exception {
        //初始化mockMVC对象
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    @Transactional
    public 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
    @Transactional
    public 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
    @Transactional
    public 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
    @Transactional
    public void deleteTest() throws Exception {
        //创建一个实体类,先插入
        StudentEntity entity = ObjectFactoryUtil.getStudentEntity();
        studentService.insert(entity);
        //获取实体类id
        Long 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);


    }
}

StudentEntityDaoTest

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.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
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
@RunWith(SpringJUnit4ClassRunner.class)
public class StudentEntityDaoTest {

    @Autowired
    private StudentEntityDao studentEntityDao;

    @Test
    @Transactional
    public void insert() {
        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
    @Transactional
    public 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
    @Transactional
    public void 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
    @Transactional
    public void findOne() {
        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
    @Transactional
    public void updateTest() {
        //先插入,再修改,确保有这条数据
        StudentEntity entity = ObjectFactoryUtil.getStudentEntity();
        studentEntityDao.insert(entity);

        //修改
        entity.setName("xiongda");
        int update = studentEntityDao.update(entity);
        Assert.assertEquals(1,update);

    }

    @Test
    @Transactional
    public void deleteTest() {
        //先插入,再删除,确保有这条数据
        StudentEntity entity = ObjectFactoryUtil.getStudentEntity();
        studentEntityDao.insert(entity);

        int delete = studentEntityDao.delete(entity.getId());
        assertThat(delete).isEqualTo(1);

    }
}

ScoreServiceTest

package com.atomintl.exchange.learn.service;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
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 {

    /*
    //方式一:使用注解
    @Mock
    private ScoreService scoreService;

     */

    @Test
    public void addScore() {
        //方式二:使用mock方法来创建一个ScoreService的对象
        ScoreService scoreService = PowerMockito.mock(ScoreService.class);

        //因为我们需要用到getInstance()方法,这是一个静态方法,所以要用到mockStatic
        PowerMockito.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);


    }

    @Test
    public void getScore() {
        //方式二,创建一个mock对象
        ScoreService scoreService = PowerMockito.mock(ScoreService.class);

        //因为我们需要用到getInstance()方法,这是一个静态方法,所以要用到mockStatic
        PowerMockito.mockStatic(ScoreService.class);

        //这里需要返回一个ScoreService对象,我们可以通过方式一和方式二两种方式来获得
        PowerMockito.when(ScoreService.getInstance()).thenReturn(scoreService);
        PowerMockito.when(scoreService.getScore()).thenReturn(BigDecimal.valueOf(100));

       assertEquals(BigDecimal.valueOf(100),scoreService.getScore());

    }


}

StudentServiceTest

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 {

    @InjectMocks
    private StudentService studentService;

    @Mock
    private StudentEntityDao studentEntityDao;



    @Test
    public 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());
    }

    @Test
    public 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);

    }

    @Test
    public 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);

    }

    @Test
    public 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());



    }

    @Test
    public 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());
    }

    @Test
    public 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());
    }
}

StudentServiceTestNoWithMock

package com.atomintl.exchange.learn.service;

/**
 * @Author TongJie Shao
 * Created by @Author  on 2020/7/20 18:21
 */

import com.atomintl.exchange.learn.dao.StudentEntityDao;
import com.atomintl.exchange.learn.entity.StudentEntity;
//import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
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.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

/**
 * @Author TongJie Shao
 * Created by @Author  on 2020/7/16 16:55
 */
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class StudentServiceTestNoWithMock {

//    @Autowired
//    private StudentEntityDao studentEntityDao;

    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentEntityDao studentEntityDao;

    @Test
    @Transactional
    public void insert() {

        /**-----------------------------测试 insert() 方式 1-------------------------------------------**/
//        StudentEntity studentEntity = new StudentEntity();
//        studentEntity.setId(3l);
//        studentEntity.setName("nateshao");
//        studentEntityDao.insert(studentEntity);

        /**-----------------------------测试 insert() 方式 2-------------------------------------------**/
        StudentEntity orgin = new StudentEntity();
        orgin.setId(10L);
        studentEntityDao.insert(orgin);
        StudentEntity result = studentEntityDao.findOne(orgin);
        assertThat(result.getId()).isEqualTo(orgin.getId());

    }

    @Test
    @Transactional
    public void insertList() {
        StudentEntity studentEntity = new StudentEntity();
        List<StudentEntity> list = new ArrayList<>();
        studentEntity.setId(10l);
        studentEntity.setName("zhangsan");
        studentEntity.setId(11l);
        studentEntity.setName("lisi");
        studentEntity.setId(12l);
        studentEntity.setName("wangwu");
        list.add(studentEntity);
        studentEntityDao.update(studentEntity);
    }
    @Test
    @Transactional
    public void findList() {
        StudentEntity studentEntity = new StudentEntity();
        List<StudentEntity> list = studentEntityDao.findList(studentEntity);
        System.out.println(list);
    }

    @Test
    @Transactional
    public void findOne() {
        StudentEntity studentEntity = new StudentEntity();
        StudentEntity studentEntity1 = studentEntityDao.findOne(studentEntity);
        System.out.println(studentEntity1);
    }

    @Test
    @Transactional
    public void update() {
        StudentEntity studentEntity = new StudentEntity();
        studentEntity.setName("tongjie1");
        studentEntity.setId(2l);
        int update = studentEntityDao.update(studentEntity);
        System.out.println(update);

    }


    @Test
    @Transactional
    public void delete() {
        studentEntityDao.delete(1l);
    }
}

ObjectFactoryUtil

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());  //将随机数设置为id
        entity.setName("xuzhi"); //设置名字
        entity.setCreateTime(new Timestamp(new Date().getTime())); //设置创建时期
        entity.setUpdateTime(new Timestamp(new Date().getTime())); //设置更新时期
        return entity;
    }



}

文章作者: 千羽
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 千羽 !
评论
  目录