1、springboot测试类无法加载mybatis的xml

(1)添加依赖(pom.xml):

1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

(2)配置mybatis的xml路径(application.yml)

注意:如果你和我是配置了多个配置文件,例如application-dev.yml、application-pro.yml,这样的,请在dev文件下在mapper-locations: classpath后有个*号,在pro文件不加*号,这样就只会在开发环境扫描当前类路径和依赖的jar包等的类路径,在生产环境只扫描项目类路径

application-dev.yml

1
2
3
4
5
mybatis:
type-aliases-package: com.sws.exam.*.entity
mapper-locations: classpath:com/sws/exam/*/mapper/xml/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

application-pro.yml

1
2
3
4
5
mybatis:
type-aliases-package: com.sws.exam.*.entity
mapper-locations: classpath*:com/sws/exam/*/mapper/xml/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

(3)编写测试类:

1
2
3
4
5
6
7
8
9
10
11
12
13
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TbUserServiceTest {

@Test
public void test {
//
}

}

其中:

@RunWith(SpringRunner.class) 是 让 JUnit 运行 Spring 的测试环境, 获得 Spring 环境的上下文的支持

@SpringBootTest // 获取启动类,加载配置,确定装载 Spring 程序的装载方法,它回去寻找 主配置启动类(被 @SpringBootApplication 注解的)