Java, 原创,

SpringBoot 单元测试写法

1.启动类Application写法

package cn.xxx.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

import tk.mybatis.spring.annotation.MapperScan;


@SpringBootApplication
@MapperScan(basePackages = {"cn.xxx.mapper"})
@ComponentScan(basePackages = {"cn.xxx.resource"})
public class AppTest {
    public static void main(String[] args) {
        SpringApplication.run(AppTest.class, args);
    }
}

Service 模块测试的写法

package cn.xxx.test;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import tk.mybatis.mapper.autoconfigure.MapperAutoConfiguration;


@ActiveProfiles("test")
@ImportAutoConfiguration(MapperAutoConfiguration.class)
@ExtendWith(SpringExtension.class)
@DisplayName("Base Test")
@SpringBootTest(classes = AppTest.class)
public abstract class BaseTest {

    @Test
    public void test() {

    }
}

基础设施模块测试写法


package cn.xxx.dao;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mybatis.spring.boot.test.autoconfigure.MybatisTest;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import tk.mybatis.mapper.autoconfigure.MapperAutoConfiguration;

@ActiveProfiles("test")
@ImportAutoConfiguration(MapperAutoConfiguration.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@MybatisTest
@ExtendWith(SpringExtension.class)
//@SpringBootTest(classes = AppTest.class)
@DisplayName("Base Test")
public abstract class BaseDAOTest {

    @Test
    public void test() {

    }
}

(196)

Related Post