栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot 单元测试(springboot项目单元测试)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot 单元测试(springboot项目单元测试)

今天在做远程调用接口测试的时候,发现restTemplate自动注入不进去

@SpringBootTest
@RunWith(SpringRunner.class)
public class testRestTemplate {
    @Autowired
    private RestTemplate restTemplate;

    @Test
    public void t1(){
        ResponseEntity forEntity = restTemplate.getForEntity("http://localhost:31001/cms/config/getmodel/5a791725dd573c3574ee333f", Map.class);
        System.out.println("++++++++++++++-----------"+forEntity);
    }
}

运行单元测试发现报错,信息如下

这时我顺着找到了启动类,我的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)

二是将测试类与要和需要注入的依赖有一样的路径,总结的不好,在本例中就是测试类的包路径和启动类的包路径一致,即问题解决

两种方法都可,根据需要处理,至此又跳一坑

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/776721.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号