鼠标放在要测试的类的类名上(代码里的类名),右键go to —test 然后新建测试,其他操作如下
1.pom.xml
一般使用idea新建一个SpringBoot web项目时,一般都会自动引入此依赖,如果没有,请手动引入。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2.测试类基类
因为测试有很多,都需要导入头文件,比较麻烦 ,建立超类,其他的只需要继承就行
package com.alibaba;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@Component //依赖注入用
@SpringBootTest(classes = App.class) //app为主程序入口类
public class TmallApplicationTests {
@Before
public void init() {
System.out.println("开始测试-----------------");
}
@After
public void after() {
System.out.println("测试结束-----------------");
}
}
3.测试类
package com.xx;
import com.zhaolong.pojo.Province;
import com.zhaolong.service.ProvinceServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ZhaolongApplicationTests extends TestFather {
@Autowired
private ProvinceServiceImpl psi;
@Test
public void testListProvince() {
List<Province> list = psi.listProvince();
for (Province p:
list) {
System.out.println(p);
}
}
}
总结
总体上来讲,springboot 单元测试相对麻烦一点点,不过有网上这些前辈,其他都不是问题了哈哈哈
参考出处:https://blog.csdn.net/weixin_39800144/article/details/79241620