使用Spring Boot进行测试时,不希望加载application.yml

时间:2018-02-14 16:47:03

标签: spring-boot spring-test spring-boot-test

如何告诉Spring只加载application-test.yml而不加载application.yml文件?

我有一个配置类:

@ActiveProfiles("test")
@SpringBootConfiguration

public class MongoTestConfig {

    @Autowired
    MongoOperations operations;
...
}

还有一个测试类:

@RunWith(SpringRunner.class)
@DataMongoTest
@SpringBootTest(classes = MongoTestConfig.class)
public class TagDefinitionRepositoryTest {
...
@Test
....
}

我试图添加:

@TestPropertySource(locations = {"classpath:application-test.yml"})
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)

到我的配置类但它不起作用:Spring仍然加载application.yml

2 个答案:

答案 0 :(得分:4)

我不认为你可以告诉Spring Boot完全忽略application.yml。但您可以做的是使用特定于测试的属性文件覆盖所有不需要的属性。

根据您发布的代码段,application-test.yml中的任何属性都将覆盖application.yml中的等效属性。

Spring Boot考虑了特定于配置文件的application-test.yml" test" (其优先级高于默认的application.yml)。不需要注释@TestPropertySource

但是,如果要为属性文件选择其他名称,则可以使用@TestProertySource,因为@TestProperySource参数中指示的文件优先于其他参数。

您可能想看一下Spring Boot external configuration rules for resolving properties

答案 1 :(得分:-1)

我最终使用@SpringBootTest而不是@DataMongoTest

@SpringBootConfiguration
@ComponentScan(basePackages = {"com.package.services"})
@EnableMongoRepositories(basePackages = {"com.package.repositories"})
public class MongoTestConfig {

private static final MongodStarter starter = MongodStarter.getDefaultInstance();
@Bean
public MongoClient mongoClient() throws IOException {
    MongodExecutable _mongodExe;
    MongodProcess _mongod;

    _mongodExe = starter.prepare(new MongodConfigBuilder()
            .version(Version.Main.V3_2)
            .net(new Net("localhost", 12345, Network.localhostIsIPv6()))
            .build());

    _mongod = _mongodExe.start();


    MongoClient _mongo = new MongoClient("localhost", 12345);

    return _mongo;

}

@Bean
public MongoDbFactory mongoDbFactory() throws IOException{
    return new SimpleMongoDbFactory(mongoClient() , "test");
}

@Bean
public MongoTemplate mongoTemplate() throws IOException {
    return new MongoTemplate(mongoDbFactory());
}

我的测试课程是:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyRepositoryTest {
...