什么是 JUnit?

  JUnit 是一个 Java 编程语言的单元测试框架。JUnit 在测试驱动的开发方面有很重要的发展,是起源于 JUnit 的一个统称为 xUnit 的单元测试框架之一。

  JUnit 促进了“先测试后编码”的理念,强调建立测试数据的一段代码,可以先测试,然后再应用。这个方法就好比“测试一点,编码一点,测试一点,编码一点……”,增加了程序员的产量和程序的稳定性,可以减少程序员的压力和花费在排错上的时间。
特点:
JUnit 是一个开放的资源框架,用于编写和运行测试。
提供注释来识别测试方法。
提供断言来测试预期结果。
提供测试运行来运行测试。
JUnit 测试允许你编写代码更快,并能提高质量。
JUnit 优雅简洁。没那么复杂,花费时间较少。
JUnit 测试可以自动运行并且检查自身结果并提供即时反馈。所以也没有必要人工梳理测试结果的报告。
JUnit 测试可以被组织为测试套件,包含测试用例,甚至其他的测试套件。
JUnit 在一个条中显示进度。如果运行良好则是绿色;如果运行失败,则变成红色。

  由于Mybatis的介绍已经很多介绍,本文就不深入介绍了,直接上代码。本文是在SpringBoot(二)SpringBoot集成Mybatis 集成上使用的,具体请看:
SpringBoot(二)SpringBoot集成Mybatis pom.xml

<!-- junjit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

这是本次的重点代码 Junit单元测试类
@SpringBootTest是SpringBoot的一个用于测试的注解,通过SpringApplication在测试中创建ApplicationContext。一般指定启动类。
@AutoConfigureMockMvc是用于自动配置MockMvc
@RunWith方法构造了一个的Servlet容器运行运行环境,并在此环境下测试。

package com.example.demo;

import com.example.demo.controller.TestController;
import com.example.demo.service.UserService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = DemoJunitApplication.class)
@RunWith(SpringRunner.class)
@Rollback
@AutoConfigureMockMvc
class DemoApplicationTests {

    @Autowired
    private TestController testController;

    @Autowired
    private UserService userService;

    @Test
    void getTest() {
        System.out.println(testController.getTest());

    }

    @Test
    void getAllUser() {
        userService.getAllUser().forEach(user -> System.out.println(user));

    }

}

DemoJunitApplication

package com.example.demo;

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

@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoJunitApplication {

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

}

TestController

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @ClassName TestController
 * @Description: TODO
 * @Date 2020/6/10
 * @Version V1.0
 **/
@Controller
@RequestMapping("/test")
public class TestController {

    @RequestMapping("hello")
    @ResponseBody
    public String  getTest(){
        return "Hello World ,This is  Test";
    }
}

UserController

package com.example.demo.controller;

import com.example.demo.module.User;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName UserController
 * @Description: TODO
 * @Date 2020/6/10
 * @Version V1.0
 **/
@RequestMapping("user")
@Controller
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("getAllUser")
    @ResponseBody
    public List<User> getAllUser(){
        return userService.getAllUser();
    }
}

User

package com.example.demo.module;

/**
 * @ClassName User
 * @Description: TODO
 * @Date 2020/6/10
 * @Version V1.0
 **/
public class User {

    private int id;

    private String name;

    private int age;

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

UserService

package com.example.demo.service;

import com.example.demo.module.User;

import java.util.List;

public interface UserService {
    List<User> getAllUser();
}

UserServiceImpl

package com.example.demo.service.impl;

import com.example.demo.mapper.UserMapper;
import com.example.demo.module.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName UserServiceImpl
 * @Description: TODO
 * @Date 2020/6/10
 * @Version V1.0
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getAllUser() {
        return userMapper.getAllUser();
    }
}

UserMapper

package com.example.demo.mapper;

import com.example.demo.module.User;

import java.util.List;

/**
 * @ClassName UserMapper
 * @Description: TODO
 * @Date 2020/6/10
 * @Version V1.0
 **/
public interface UserMapper {
    List<User> getAllUser();
}

UserMapper.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.example.demo.mapper.UserMapper">
  <resultMap id="BaseResultMap" type="com.example.demo.module.User">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="age" jdbcType="INTEGER" property="age" />
  </resultMap>
  <sql id="Base_Column_List">
    id, name, age
  </sql>
  <select id="getAllUser" resultType="com.example.demo.module.User">
    SELECT * FROM user
  </select>
</mapper>

配置文件 application.properties

server.port=8888

# mysql
spring.datasource.url=jdbc:mysql://39.106.126.132:3306/test?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

mybatis.mapper-locations=classpath*:mapper/**/*.xml

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>junit</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>junit</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- commons start -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>
        <!-- commons end -->

        <!-- mybatis start-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <!-- druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.11</version>
        </dependency>
        <!-- mybatis end-->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- junjit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

在DemoApplicationTests单元测试类中选择需要进行测试代码,例如:getTest()方法上有@Test注解,在方法附近右击Run

装载SpringBoot运行Junit测试 spring boot junit java_编程语言


输出信息为:

装载SpringBoot运行Junit测试 spring boot junit java_spring boot_02


配置成功。

再次测试获取所有的用户信息接口,在单元测试中操作如下:

装载SpringBoot运行Junit测试 spring boot junit java_spring boot_03

获取的所有的用户信息如下:

装载SpringBoot运行Junit测试 spring boot junit java_java_04


SpringBoot集成JUnit单元测试项目就完成了。感谢点赞关注交流。