SpringBoot+Maven项目进行junit单元测试-入门篇
配置与安装
- 安装插件 File - Settings - Plugins 搜索JunitGenerator V2.0 然后点Install,再进入Other Settings 设置Output Path 中测试文件存放位置(我的位置是src/test,所以我这里添加了…/…/),然后选择Junit4 设置默认想要自动生成的内容
方便复制~附上代码
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;
import java.util.Random;
@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentServiceImplTest {
@Autowired
StudentServiceImpl studentService;
@Before
public void before() throws Exception {
}
@After
public void after() throws Exception {
}
/**
* 查询学生信息
* Method: loadStudentInfos()
*/
@Test
public void testLoadStudentInfos() throws Exception {
List<Student> list = studentService.loadStudentInfos();
Assert.assertThat(list, Matchers.notNullValue());
}
}
- pom.xml引入jar
<!-- junit相关jar包 -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
- 配置测试文件目录 File - Project Structure - Modules - 选择test文件夹在点击Tests
- 开始自动生成test文件,选中要测试的类 alt+inser(或者鼠标右击) - Generater… - JUnit Test - JUnit 4 就会自动在test文件夹下对应包下生成对应名字的测试类
然后直接运行就好了。绿油油的通过~
基本上都是自动生成的,所以写的很少,也很方便,入个门是不是超级简单,关于Assert断言,暂时不多说,可以自行百度(主要是我这个小白也还没搞明白)
自己写了一个小demo,地址是https://download.youkuaiyun.com/download/notHavaBug/14949381?spm=1001.2014.3001.5503