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 是執行測試程序的引導類

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM