How do I configure my Spring Boot application so that when I run unit tests it will use in-memory database such as H2/HSQL but when I run Spring Boot application it will use production database [Postgre/MySQL] ?
相关问题
- java.lang.IllegalArgumentException: Cannot set to
- Spring Data MongoDB - lazy access to some fields
- Declaring an explict object dependency in Spring
- Decoding body parameters with Spring
- Spring Integration - Inbound file endpoint. How to
相关文章
- java JDK动态代理和cglib动态代理最后获取的代理对象都为null的问题
- org.xml.sax.SAXParseException; lineNumber: 7; colu
- SpringMVC如何把File封装到Map中?
- Spring: controller inheritance using @Controller a
- How to load @Configuration classes from separate J
- Java spring framework - how to set content type?
- Java/Spring MVC: provide request context to child
- Spring 5 Web Reactive - Hot Publishing - How to us
@Sanjay has one way to put it but I find it confusing. You could just as well have only a
production
profile that you enable when you're in production, something like:And don't specify anything else. If you add an embedded database in
test
scope, it will be available in your tests. If you run your tests with the default profile (no customization whatsoever), it won't find any database information (since these are stored in theproduction
profile). In that case, it will try to find an embedded database and start it for you. If you need more customization for some reason, you can have aapplication-test.properties
for those (you'll need to addActiveProfiles("test")
to your test(s).Simplest solution:
1) in src/main/resources have application.properties (production config):
and application-test.properties with HSQL config like:
2) Add HSQL dependency in pom.xml if you don't have it already.
3) Annotate your test class with @ActiveProfiles("test").
Worked like charm in my case.
Simple solution if building with
maven
: just place anapplication.properties
file undersrc/test/resources
and edit as appropriate for testing.The Spring (Boot) Profile mechanism is a pretty powerful tool that, in scope, goes way beyond "swapping settings between test time and run time". Although, clearly, as demonstrated, it can do that also :)
Spring profiles can be used for this. This would be a specific way:
Have environment specific properties files:
application.properties:
application-dev.properties
application-test.properties
Have both MySQL and H2 drivers in
pom.xml
, like this:Last but not the least, annotate Test classes with
@ActiveProfiles("test")
.Another approach is to add the annotation
@AutoConfigureTestDatabase
to you test class. My tests usually look like this: