Spring Boot单元测试实战

发布时间:2023-01-28 20:30

一 pom


     4.0.0
     org.fkit
     springboottest
     0.0.1-SNAPSHOT
     jar
     springboottest
     http://maven.apache.org
     
     
           org.springframework.boot
           spring-boot-starter-parent
           2.0.0.RELEASE
           
     
     
           UTF-8
           UTF-8
           1.8
     
     
           
           
                org.springframework.boot
                spring-boot-starter-web
           
           
           
                org.springframework.boot
                spring-boot-starter-thymeleaf
           
           
           
                org.springframework.boot
                spring-boot-starter-test
                test
           
           
                mysql
                mysql-connector-java
           
           
                org.springframework.boot
                spring-boot-starter-data-jpa
           
           
                junit
                junit
                test
           
     

二 启动类

package org.fkit.springboottest;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class App
{
    public static void main( String[] args )
    {
         SpringApplication.run(App.class, args);
    }
}

三 持久化类

package org.fkit.springboottest.bean;


import java.io.Serializable;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name="tb_student")
public class Student implements Serializable{
    
    private static final long serialVersionUID = 1L;
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name ;
    private String address ;
    private int age ;
    private char sex;
    public Student() {


    }
    public Student(String name, String address, int age, char sex) {
        super();
        this.name = name;
        this.address = address;
        this.age = age;
        this.sex = sex;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public char getSex() {
        return sex;
    }
    public void setSex(char sex) {
        this.sex = sex;
    }
}

四 控制器

package org.fkit.springboottest.controller;
import java.util.HashMap;
import java.util.Map;


import javax.annotation.Resource;


import org.fkit.springboottest.bean.Student;
import org.fkit.springboottest.service.SchoolService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/student")
public class StudentController {
    @Resource
    private SchoolService shcoolService;
    
    @PostMapping(value="/save")
    public Map save(@RequestBody Student stu) {
        shcoolService.save(stu);
        Map params = new HashMap<>();
        params.put("code", "success");
        return params;
    }
    
    /**
     * 获取学生信息
     * @param id
     */
    @GetMapping(value="/get/{id}")
    @ResponseBody
    public Student qryStu(@PathVariable(value = "id") Integer id){
        Student stu = shcoolService.selectByKey(id);
        return stu;
    }
    
}

五 service

package org.fkit.springboottest.service;


import java.util.Optional;


import javax.annotation.Resource;


import org.fkit.springboottest.bean.Student;
import org.fkit.springboottest.repository.StudentRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class SchoolService {
    
    // 定义数据访问层接口对象
    @Resource
    private StudentRepository studentRepository;
    
    @Transactional
    public void save(Student stu) {
        studentRepository.save(stu);
    }

    public Student selectByKey(Integer id) {
        Optional op = studentRepository.findById(id);
        return op.get();
    }
}

六 Repository

package org.fkit.springboottest.repository;
import org.fkit.springboottest.bean.Student;
import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository extends JpaRepository {
    
}

七 测试

1 控制器测试

package org.fkit.springboottest;
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.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;


@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class StudentControllerTest {
    
    // 注入Spring容器
    @Autowired
    private WebApplicationContext wac;
    // MockMvc实现了对Http请求的模拟
    private MockMvc mvc;
    @Before
    public void setupMockMvc(){
        // 初始化MockMvc对象
        mvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }
    
    /**
     * 新增学生测试用例
     * @throws Exception
     */
    @Test
    public void addStudent() throws Exception{
        String json="{\"name\":\"孙悟空\",\"address\":\"花果山\",\"age\":\"700\",\"sex\":\"男\"}";
        mvc.perform(MockMvcRequestBuilders.post("/student/save")
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .accept(MediaType.APPLICATION_JSON_UTF8)
                    .content(json.getBytes()) //传json参数
            )
           .andExpect(MockMvcResultMatchers.status().isOk())
           .andDo(MockMvcResultHandlers.print());
    }


    /**
     * 获取学生信息测试用例
     * @throws Exception
     */
    @Test
    public void qryStudent() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/student/get/1")
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .accept(MediaType.APPLICATION_JSON_UTF8)
            )
           .andExpect(MockMvcResultMatchers.status().isOk())
           .andExpect(MockMvcResultMatchers.jsonPath("$.name").value("孙悟空"))
           .andExpect(MockMvcResultMatchers.jsonPath("$.address").value("花果山"))
           .andDo(MockMvcResultHandlers.print());
    }
}

2 service测试

package org.fkit.springboottest;
import org.fkit.springboottest.bean.Student;
import org.fkit.springboottest.service.SchoolService;
import org.hamcrest.CoreMatchers;
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.SpringRunner;


@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentServiceTest {
    
    // 注入Service
    @Autowired
    private SchoolService studentService;


    @Test
    public void findOne() throws Exception {
         Student stu = studentService.selectByKey(1);
         Assert.assertThat(stu.getName(),CoreMatchers.is("孙悟空"));
    }
}

八 配置

########################################################
### \u6570\u636E\u6E90\u4FE1\u606F\u914D\u7F6E
########################################################
# \u6570\u636E\u5E93\u5730\u5740
spring.datasource.url =  jdbc:mysql://localhost:3306/springboottest
# \u7528\u6237\u540D
spring.datasource.username =root
# \u5BC6\u7801
spring.datasource.password =
# \u6570\u636E\u5E93\u9A71\u52A8
spring.datasource.driverClassName = com.mysql.jdbc.Driver
#  \u6307\u5B9A\u8FDE\u63A5\u6C60\u4E2D\u6700\u5927\u7684\u6D3B\u8DC3\u8FDE\u63A5\u6570.
spring.datasource.max-active=20
#  \u6307\u5B9A\u8FDE\u63A5\u6C60\u6700\u5927\u7684\u7A7A\u95F2\u8FDE\u63A5\u6570\u91CF.
spring.datasource.max-idle=8
#  \u6307\u5B9A\u5FC5\u987B\u4FDD\u6301\u8FDE\u63A5\u7684\u6700\u5C0F\u503C
spring.datasource.min-idle=8
#  \u6307\u5B9A\u542F\u52A8\u8FDE\u63A5\u6C60\u65F6\uFF0C\u521D\u59CB\u5EFA\u7ACB\u7684\u8FDE\u63A5\u6570\u91CF
spring.datasource.initial-size=10
########################################################
### JPA\u6301\u4E45\u5316\u914D\u7F6E
########################################################
# \u6307\u5B9A\u6570\u636E\u5E93\u7684\u7C7B\u578B
spring.jpa.database = MySQL
#  \u6307\u5B9A\u662F\u5426\u9700\u8981\u5728\u65E5\u5FD7\u4E2D\u663E\u793Asql\u8BED\u53E5
spring.jpa.show-sql = true
#  \u6307\u5B9A\u81EA\u52A8\u521B\u5EFA|\u66F4\u65B0|\u9A8C\u8BC1\u6570\u636E\u5E93\u8868\u7ED3\u6784\u7B49\u914D\u7F6E\uFF0C\u914D\u7F6E\u6210update
#  \u8868\u793A\u5982\u679C\u6570\u636E\u5E93\u4E2D\u5B58\u5728\u6301\u4E45\u5316\u7C7B\u5BF9\u5E94\u7684\u8868\u5C31\u4E0D\u521B\u5EFA\uFF0C\u4E0D\u5B58\u5728\u5C31\u521B\u5EFA\u5BF9\u5E94\u7684\u8868
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
# \u6307\u5B9A\u547D\u540D\u7B56\u7565
spring.jpa.hibernate.naming-strategy =  org.hibernate.cfg.ImprovedNamingStrategy
# \u6307\u5B9A\u6570\u636E\u5E93\u65B9\u8A00
spring.jpa.properties.hibernate.dialect =  org.hibernate.dialect.MySQL5Dialect

九 创建数据库springboottest

十 测试结果

控制器和service测试通过

 

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号