2016-04-19 63 views
0

我有一个标准的spring-boot应用程序,我想为生产环境使用MS SQL数据库,而对于集成测试,我想使用h2数据库。问题是我无法知道如何覆盖默认的application.properties文件。尽管我试图遵循一些教程,我没有拿出合适的解决方案...也许我只是失去了一些东西......覆盖在spring-boot应用程序中进行集成测试的application.properties

主类:

@SpringBootApplication 
@EnableTransactionManagement 
public class MyApplication { 
    public static void main(String[] args) { 
     SpringApplication.run(MyApplication .class, args); 
    } 
} 

和类测试:

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration(classes = MyApplication.class) 
@WebIntegrationTest 
public class MessageControllerTest { 

    @Autowired 
    MessageRepository messageRepository; 
    ... 
    ... 
    ... 
    @Test 
    public void testSomething(){ 
    ... 
    ... 
    ... 
    ... 
    } 
} 

所以,问题是,如何强制春季启动运行测试的时候,而不是application.properties,应在运行时使用使用application-test.properties文件。

我试过例如用@TestPropertySource(locations="classpath:application-test.properties")替换@WebIntegrationTest注释,但是这导致java.lang.IllegalStateException: Failed to load ApplicationContext

+0

您是否尝试过使用特定配置文件? –

+0

不,因为我对这项技术相当陌生,实际上我不知道什么才是最好的方法来实现这个目标。 – Dworza

+0

上面的评论*是你的问题的答案,根据文档:http:/ /docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties – kryger

回答

0

(具有大的测试类我认为,当这不适合)其实这很容易......经过几个小时的尝试,我意识到我只需要用@ActiveProfiles("test")注释来注释我的测试课程。

@ActiveProfiles("test") 
    @RunWith(SpringJUnit4ClassRunner.class) 
    @SpringApplicationConfiguration(classes = MyApplication.class) 
    @WebIntegrationTest 
    public class MessageControllerTest { 

     @Autowired 
     MessageRepository messageRepository; 
     ... 
     ... 
     ... 
     @Test 
     public void testSomething(){ 
     ... 
     ... 
     ... 
     ... 
     } 
    } 
+1

稍微好一点的方法是做这样的事情:@ActiveProfiles(AppProfile.TEST).ie创建一个包含所有可能状态的枚举。它节省了更改时间并使跟踪配置文件类型更容易。还要创建一个抽象的BaseTest类,并将所有这些设置放在那里。现在扩展它的所有测试用例。 –

0

假设您的应用程序中有一个application-test.properties文件。

我这样做有两种方式:

1.CLI JVM参数数量

mvn spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=test 
  • 添加application-test.properties作为活性轮廓。
  • 在application.properties中添加spring.profiles.active=test,它将加载您的application-test.properties文件。

  • 正如你指出,在你的答案注释一类测试具有特定有效简@ActiveProfiles("test")
  • +0

    请确认答案是否适合给你 –

    相关问题