接着上一篇: 《springboot学习笔记 02》--访问数据库
需求, 对StudentService的getStudent()方法进行单元测试
1, pom.xml添加依赖
<!-- 单元测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2, 新建测试类ServiceTest
@RunWith(SpringRunner.class)
@SpringBootTest
public class ServiceTest {
@Autowired
private StudentService service;
@Test
public void testGetStudent(){
List<Student> list = service.getStudent();
System.out.println(list.get(0).getName());
Assert.assertEquals("Tom2", list.get(0).getName());
}
}
PS: 若出现注解标签无法导入的问题, 需要maven --> update project;
3, 测试
选中目标对象(类or方法) --> run as Junit Test
PS:
若出现报错: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or ....
解决办法: 调整启动类Demo.java的位置, 将项目启动类转放在根目录下, 重新启动测试
测试通过即ok !