Spring (Boot) Test Memo

440 阅读1分钟
  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 比较方便