需求

springboot项目启动配置过多,每次启动测试类需要加载整个环境配置,导致启动缓慢,不利于快速测试,部分场景只需要少量以来配置,因此可自定义加载配置。

方法

这里以测试controller为例,由于只测试controller,因此可以不需要启动什么数据库、缓存之类的,只需要加载基础的bean对象即可。

package org.**.aop;

import org.**.controller.LogController;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.*;
import org.springframework.test.web.servlet.result.*;

@WebMvcTest(LogController.class)
@ContextConfiguration(classes = Configuration.class)
class LogAspectTest {

    @Autowired
    private MockMvc mvc;

    @Test
    void given_login_when_request_then_save_this_request() {
        Assertions.assertTrue(true);
    }
}
package org.**.aop;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigurationExcludeFilter;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;

/**
 * @author wanghengzhi
 * @since 2021/11/8 15:18
 */
@SpringBootConfiguration
@ComponentScan(excludeFilters = { @ComponentScan.Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @ComponentScan.Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) },
        basePackages = "org.**")
public class Configuration {

}

方法梳理:

在测试类中,指定启动spring环境上下文配置,并指向自定义配置文件,这里配置文件类似于springboot默认启动类,可以在这里配置依赖配置。