zoukankan      html  css  js  c++  java
  • 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 是执行测试程序的引导类
    写博客是为了总结记录,而不应为了花里胡哨的标榜什么。比如写了一个算法,尽量联系下应用场景;看了一段源码,想一下对应用层调用有什么影响,做到学以致用,避免眼高手低。
  • 相关阅读:
    【Dubbo 源码解析】08_Dubbo与Spring结合
    【Dubbo 源码解析】07_Dubbo 重试机制
    【Dubbo 源码解析】06_Dubbo 服务调用
    【Dubbo 源码解析】05_Dubbo 服务发现&引用
    【Dubbo 源码解析】04_Dubbo 服务注册&暴露
    【Dubbo 源码解析】03_Dubbo Protocol&Filter
    【Dubbo 源码解析】02_Dubbo SPI
    Hadoop(十五)MapReduce程序实例
    Hadoop(十四)MapReduce原理分析
    Hadoop(十三)分析MapReduce程序
  • 原文地址:https://www.cnblogs.com/cappuccino-jay/p/14979516.html
Copyright © 2011-2022 走看看