springboot 的测试
需要的以来jar
包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<!--test表明只能在test包下才可以用的jar,在非test包下不可用-->
<scope>test</scope>
</dependency>
优雅的方法:
①先在pom.xml
文件中引入上面的jar,然后在test
(一定是与main
同级的那个test
下哦)的包才可以。
②然后新建一个TestBean
类
③用其他需要测试的类继承这个TestBean
类
package org.my.test;
// TestBean类
import org.junit.runner.RunWith;
import org.my.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
//作用:让当前类在容器环境下进行测试
@RunWith(SpringRunner.class)
//作用:声明当前类是springboot的测试类并且获取入口类上的相关信息 SpringBootApplication是入口类类名
@SpringBootTest(classes = SpringBootApplication.class)
public class TestBean {
}
注意:子类的类名一定是不能够和main包下的任意类同名,否则报错,这是一个坑的
package org.my.service;
import lombok.extern.log4j.Log4j;
import org.junit.Test;
import org.my.entity.Province;
import org.my.test.TestBean;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
@Log4j
public class TestProvinceService extends TestBean {
@Autowired
ProvinceService provinceService;
@Test
public void testSelectAllProvinces() {
List<Province> provinceList = provinceService.selectAllProvinces();
log.debug("testSelectAllProvinces");
System.out.println("testSelectAllProvinces");
for (Province province : provinceList) {
System.out.println(province);
}
}
}
简单粗暴的方法:①导入依赖;
②直接在test
包下新建测试类 加上下面的两个注解,然后就可以直接写测试方法了。当然了,你的每一个测试类都是需要添加上这两个注解哦
package org.my.test;
// TestBean类
import org.junit.runner.RunWith;
import org.my.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class) //作用:让当前类在容器环境下进行测试
@SpringBootTest(classes = SpringBootApplication.class)//作用:声明当前类是springboot的测试类并且获取入口类上的相关信息 SpringBootApplication是入口类类名
public class TestBean {
}