0%

Spring Boot Test无法自动注入@Autowired

Springboot 版本 2.1.5.RELEASE

引用的 spring-boot-starter-test 版本为:2.1.2.RELEASE

依赖的 junit 版本为 4.12

必须要按如下写注解,才可以把类注入成功。

1
2
3
4
5
6
7
8
9
10
11
12
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootApplication.class)
public class ControllerTests {

@Autowired
private UserController userController;

@Test
public void test() {
System.out.println(userController);
}
}
  • 需要写 @RunWith 注解
  • @SpringBootTest 注解需要添加 classes 属性,值为启动类的 class 对象。
  • test() 方法必须为 public

上述几点在新版本的 Springboot 中(比如2.2及以上)可能有变化。