提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
当我们在使用单元测试的时候,需要@Resource或者@Autowired等注入数据时,最后执行发现对象无法注入,下面是其中一种解决方案。
提示:以下是本篇文章正文内容,下面案例可供参考
二、代码实例
1.问题代码
报错之前的代码:
@SpringBootTest
public class Line {
@Resource
private Compute compute;
@Resource
private ProjectService projectService;
@Test
public void testComputeLine() {
String projectName = projectService.getProjectName();
System.out.println(projectName);
}
}
2.解决
代码如下(示例):
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {LreApplication.class})
public class Line {
@Resource
private GanSuComputeImpl ganSuCompute;
@Resource
private ProjectService projectService;
@Test
public void testComputeLine() {
String projectName = projectService.getProjectName();
System.out.println(projectName);
}
总结
添加 @RunWith(SpringRunner.class) @SpringBootTest(classes = {LreApplication.class})两个注解即可
注意:LreApplication.class是我项目中的主启动类,使用是需要更换自己项目的主启动类。