今天在做远程调用接口测试的时候,发现restTemplate自动注入不进去
@SpringBootTest
@RunWith(SpringRunner.class)
public class testRestTemplate {
@Autowired
private RestTemplate restTemplate;
@Test
public void t1(){
ResponseEntity
运行单元测试发现报错,信息如下
这时我顺着找到了启动类,我的RestTemplate在启动类中注册的
@SpringBootApplication
public class CmsApplication {
public static void main(String[] args) {
SpringApplication.run(CmsApplication.class,args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}
}
如果将 @SpringBootTest注解修改classes默认属性,即
@SpringBootTest(classes = CmsApplication.class)
再次运行单元测试便成功了,之前错误的原因在于我是在我的SpringBoot启动类(CmsApplication)中注入的RestTemplate,而我的测试类与CmsApplication启动类所属包名不一致,即测试类中@SpringBootTest注解会默认扫描相同包路径下的类,及扫描不到我的启动类,即RestTemplate无法注入
想到这里我找到了两种解决办法,一是修改@SpringBootTest的默认classes属性,如下
@SpringBootTest(classes = CmsApplication.class)
二是将测试类与要和需要注入的依赖有一样的路径,总结的不好,在本例中就是测试类的包路径和启动类的包路径一致,即问题解决
两种方法都可,根据需要处理,至此又跳一坑



