SpringBoot的单元测试

2021/7/6 23:36:31

本文主要是介绍SpringBoot的单元测试,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

对于SpringBoot项目如何使用SpringBoot的单元测试

创建一个SpringBoot的Maven项目

SpringBoot的单元测试需要额外添加的依赖是:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

Javabean类:Book.java

package com.lzumetal.springboot.demodatabase.entity;

public class Book {

    private Integer id;     //数据库主键id标识
    private String name;    //书名
    private String author;  //作者
    private Double price;   //价格

    //get、set方法省略
}

dao类:BookMapper.java

package com.lzumetal.springboot.demodatabase.mapper;


import com.lzumetal.springboot.demodatabase.entity.Book;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface BookMapper {

    int insert(Book record);
    List<Book> selectAll();
    Book getById(@Param(value = "id") Integer id);
}

对应的xml映射文件:BookMapper.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.lzumetal.springboot.demodatabase.mapper.BookMapper">
  <resultMap id="BaseResultMap" type="Book">
    <result column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="author" jdbcType="VARCHAR" property="author" />
    <result column="price" jdbcType="DOUBLE" property="price" />
  </resultMap>
  <insert id="insert" parameterType="Book">
    insert into book (id, name, author, 
      price)
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{author,jdbcType=VARCHAR}, 
      #{price,jdbcType=DOUBLE})
  </insert>
  <select id="selectAll" resultMap="BaseResultMap">
    select id, name, author, price
    from book
  </select>
  <select id="getById" resultMap="BaseResultMap">
    select id, name, author, price
    from book
    WHERE id = #{id}
  </select>
</mapper>

Controller类:BookController.java

package com.lzumetal.springboot.demodatabase.controller;

import com.google.gson.Gson;
import com.lzumetal.springboot.demodatabase.entity.Book;
import com.lzumetal.springboot.demodatabase.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Created by liaosi on 2017/9/26.
 */
@RestController
public class BookController {

    private static Gson gson = new Gson();

    @Autowired
    private BookService bookService;

    /**
     * GET请求+@PathVariable
     * @param id
     * @return
     */
    @RequestMapping(value = "/getBook/{id}", method = RequestMethod.GET)
    public String getBookInfo(@PathVariable("id") Integer id) {
        return gson.toJson(bookService.getById(id));
    }


    /**
     * GET请求
     * @param id
     * @return
     */
    @RequestMapping(value = "/getBookInfo2", method = RequestMethod.GET)
    public String getBoodInfo2(Integer id, String name) {
        Book book = new Book();
        book.setId(id);
        book.setName(name);
        return gson.toJson(book);
    }


    /**
     * 普通form表单POST请求
     * @param id
     * @return
     */
    @RequestMapping(value = "/postBookInfo", method = RequestMethod.POST)
    public String postBoodInfo(Integer id) {
        return gson.toJson(bookService.getById(id));
    }


    /**
     * POST请求,参数为json格式
     * @param book
     * @return
     */
    @RequestMapping(value = "/postJson", method = RequestMethod.POST)
    public Book postJson(@RequestBody Book book) {
        return book;
    }

}

SpringBoot项目的启动类:StartupApplication.java

package com.lzumetal.springboot.demodatabase;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
// mapper 接口类包扫描
@MapperScan(basePackages = "com.lzumetal.springboot.demodatabase.mapper")
public class StartupApplication {

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

测试类

测试Service或者Controller

MainTest.java

package com.lzumetal.springboot.demodatabase.test;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lzumetal.springboot.demodatabase.StartupApplication;
import com.lzumetal.springboot.demodatabase.controller.BookController;
import com.lzumetal.springboot.demodatabase.entity.Book;
import com.lzumetal.springboot.demodatabase.service.BookService;
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;

import java.util.List;

/*
https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4
MOCK —提供一个Mock的Servlet环境,内置的Servlet容器并没有真实的启动,主要搭配使用@AutoConfigureMockMvc

RANDOM_PORT — 提供一个真实的Servlet环境,也就是说会启动内置容器,然后使用的是随机端口
DEFINED_PORT — 这个配置也是提供一个真实的Servlet环境,使用的默认的端口,如果没有配置就是8080
NONE — 这是个神奇的配置,跟Mock一样也不提供真实的Servlet环境。
 */

@RunWith(SpringRunner.class)
@SpringBootTest(classes = StartupApplication.class)
public class MainTest {

    private static Gson gson = new GsonBuilder().setPrettyPrinting().create();

    @Autowired
    private BookService bookService;

    @Autowired
    private BookController bookController;


    @Test
    public void testBookService() {
        List<Book> allBooks = bookService.getAllBooks();
        System.out.println(gson.toJson(allBooks));
    }

    @Test
    public void testBookController() {
        String s = bookController.getBookInfo(1);
        System.out.println(s);
    }

}
  • @RunWith 是junit提供的注解,表示该类是单元测试的执行类
  • SpringRunner是spring-test提供的测试执行单元类(是Spring单元测试中SpringJUnit4ClassRunner的新名字)
  • SpringBootTest 是执行测试程序的引导类

 



这篇关于SpringBoot的单元测试的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程