I develop web app with Spring Boot. I have problem with unit test for web layer. For these tests I'm using annotation @WebMvcTest
. Problem is that my main configuration class contains @PropertySource
with java arg, which contains path to external properties file, and when I start my unit web test, error is occured that this java arg can't be parsed(of course I can add this java arg to run configuration of my test, but my web unit tests don't need this file).
My main config class:
@SpringBootApplication
@PropertySource(value = {"${pathto.configfile}"})
@EnableAspectJAutoProxy
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
My first solution was to create separate configuration class with "!test"
profile, and relocate @PropertySource("..")
to it. And to my unit test add @ActiveProfiles("test")
My second Configuration class:
@Configuration
@Profile({"!test"})
@PropertySource(value = {"${pathto.configfile}"})
public class PropertyConfiguration {
}
For unit web test this solution works very good. But new problem appears in starting of my web app. In my external properties file I have property spring.profiles.active
. To this property I assign or db
or file
value. Depending on its value, apropriate implementation of Repository is created and injected to my service layer. When value is db
, app starts good, but when value is file
error is being thrown: NoSuchBeanDefinitionException
.
When I come back to my previous version(without second configuration file), app starts good in both cases(but not web unit tests)
So, explain please, why when value of spring.profiles.active=db
, app starts good, but when spring.profiles.active=file
- failed.And how I can solve my task? I attempted to find how I can add other application context to my web unit tests, but I didn't find. Any idea?:)
For my database repositories I'm using Spring Data JPA, so I don't create implementation of these repositories, but I create implementations of my file repositories, and my implementations had @Profile("file")
. After deleting this annotation from implementations, it leaved only on interfaces. I don't know why one config class worked, but two classes didn't. But problem is solved)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.