SpringBoot测试类中如何实现@Autowired自动注入功能而无需手动编写setter方法?
- 内容介绍
- 文章标签
- 相关推荐
本文共计295个文字,预计阅读时间需要2分钟。
测试类注解说明:使用`@RunWith(SpringRunner.class)`和`@SpringBootTest`进行测试时,不需要手动注入,只需在`@SpringBootTest`中指定启动类即可。示例如下:
java@SpringBootTest(classes=Application.class)@RunWith(SpringRunner.class)public class MyTest { // 测试代码}
原来的测试类的注解:
@RunWith(SpringRunner.class) @SpringBootTest
一直没法自动注入,后来在@SpringBootTest,
加入启动类Application后就可以了
@RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class)
补充:spring boot项目单元测试时,@Autowired无法注入Service解决方式
首先确认:
测试类所在包名要和启动类一致
测试类注解正确
@SpringBootTest(classes = {BiDataTaskApplication.class}) @RunWith(SpringRunner.class)
费了半天劲,才找到原因,idea自动创建的测试类 @Test注解,使用的是 import org.junit.jupiter.api.Test;
应改成:
import org.junit.Test;
idea为什么这样,还不确定,有知道的大佬麻烦回复下!
正确配置截图:
以上为个人经验,希望能给大家一个参考,也希望大家多多支持易盾网络。如有错误或未考虑完全的地方,望不吝赐教。
本文共计295个文字,预计阅读时间需要2分钟。
测试类注解说明:使用`@RunWith(SpringRunner.class)`和`@SpringBootTest`进行测试时,不需要手动注入,只需在`@SpringBootTest`中指定启动类即可。示例如下:
java@SpringBootTest(classes=Application.class)@RunWith(SpringRunner.class)public class MyTest { // 测试代码}
原来的测试类的注解:
@RunWith(SpringRunner.class) @SpringBootTest
一直没法自动注入,后来在@SpringBootTest,
加入启动类Application后就可以了
@RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class)
补充:spring boot项目单元测试时,@Autowired无法注入Service解决方式
首先确认:
测试类所在包名要和启动类一致
测试类注解正确
@SpringBootTest(classes = {BiDataTaskApplication.class}) @RunWith(SpringRunner.class)
费了半天劲,才找到原因,idea自动创建的测试类 @Test注解,使用的是 import org.junit.jupiter.api.Test;
应改成:
import org.junit.Test;
idea为什么这样,还不确定,有知道的大佬麻烦回复下!
正确配置截图:
以上为个人经验,希望能给大家一个参考,也希望大家多多支持易盾网络。如有错误或未考虑完全的地方,望不吝赐教。

