11-SpringBoot整合Junit

SpringBoot整合Junit

实现步骤

  • 搭建SpringBoot工程
  • 引入starter-test起步依赖
  • 编写测试类
  • 添加测试相关注解
  • @RunWith(SpringRunner.class)
  • @SpringBootTest(classes = 启动类.class)
  • 编写测试方法

实现案例

1.搭建SpringBoot-test工程


11-SpringBoot整合Junit_junit11-SpringBoot整合Junit_单元测试_02

不选择依赖,直接创建。


11-SpringBoot整合Junit_spring boot_03

2. 引入starter-test起步依赖


11-SpringBoot整合Junit_junit_04

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

3.  编写 UserService 类,用于验证依赖注入


11-SpringBoot整合Junit_单元测试_05

package com.lijw.springboottest;

import org.springframework.stereotype.Service;

@Service
public class UserService {

public String findAll(){
return "findAll";
}

}

注意:要将 UserService 等类写在 ​​package com.lijw.springboottest​​ 下,如果写到其他包,例如:com.lijw.service ,那么默认 Bean 扫描不到。

4. 编写测试类


11-SpringBoot整合Junit_spring_06

package com.lijw.springboottest;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest(classes = SpringbootTestApplication.class)
public class UserServiceTest {

@Autowired
UserService userService;

@Test
public void testFindAll(){
System.out.println(userService.findAll());
}
}

5. 执行测试


11-SpringBoot整合Junit_junit_07

6.如果测试类与SpringBoot应用类在同一个package下,可以省略 (classes = SpringbootTestApplication.class)


11-SpringBoot整合Junit_java_08