Spring Boot单元测试实战

一 pom

<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>org.fkit</groupId>
     <artifactId>springboottest</artifactId>
     <version>0.0.1-SNAPSHOT</version>
     <packaging>jar</packaging>
     <name>springboottest</name>
     <url>http://maven.apache.org</url>
     <!-- spring-boot-starter-parent是Spring Boot的核心启动器,  包含了自动配置、日志和YAML等大量默认的配置,大大简化了我们的开发。
           引入之后相关的starter引入就不需要添加version配置, spring  boot会自动选择最合适的版本进行添加。 -->
     <parent>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-parent</artifactId>
           <version>2.0.0.RELEASE</version>
           <relativePath />
     </parent>
     <properties>
           <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
           <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
           <java.version>1.8</java.version>
     </properties>
     <dependencies>
           <!-- 添加spring-boot-starter-web模块依赖 -->
           <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
           </dependency>
           <!-- 添加spring-boot-starter-thymeleaf模块依赖 -->
           <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
           </dependency>
           <!-- spring-boot-starter-test 依赖.... -->
           <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
           </dependency>
           <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
           </dependency>
           <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
           </dependency>
           <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <scope>test</scope>
           </dependency>
     </dependencies>
</project>

二 启动类

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<String,Object> save(@RequestBody Student stu) {
        shcoolService.save(stu);
        Map<String,Object> 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<Student> 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<Student, Integer> {
    
}

七 测试

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测试通过

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值