阅读 63

Spring (Boot) Test Memo

  1. @SpringBootTest 替代了老版本的@IntegrationTest, 其包括了Auto Configuration, Package Scan等等默认配置,但是对于没有SpringBootApplication类,却需要Spring Context来加载Bean, Autowired的情况,可以通过 @ContextConfiguration(locations = {"classpath:/xxx.xml"}) 来指定Context配置

  2. @SpringBootTest是个大集合,但有的情况不想全要,可以通过Overide的方式,比如再加一个@EnableAutoConfiguration(exclude = {MongoAutoConfiguration.class}), 但如果需要exclude多的话,就会很麻烦,感觉就不想直接@SpringBootTest

  3. 对于不加@SpringBootTest, 但需要@ExtendWith(SpringExtension.class) -- JUnit5, 或者 @RunWith(SpringJUnit4ClassRunner.class) -- JUnit4的情况, Spring默认只会读取application-xxx.properties 作为PropertySource,其中xxx = Active Profile Name, 不会去读yml, 如果需要支持读yml,则要另外实现,不然在代码中用@Value 是无法正确注入对应value的

public class YamlPropertyLoaderFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        if (resource == null){
            return super.createPropertySource(name, resource);
        }

        return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource(), null);
    }
}复制代码

然后再通过注解申明

@PropertySource(value = "classpath:application-test.yml", factory = YamlPropertyLoaderFactory.class)复制代码

但个人觉得有点麻烦

所以个人prefer,如果可以直接用@SpringBootTest的情况直接用,PropertySource也可以直接用.yml, 如果不用@SpringBootTest,那么test的PropertySource直接用.properties 比较方便


作者:Gee
链接:https://juejin.cn/post/7023564522862411813


文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐