Springboot loading wrong config despite being explicit - java

I have the following Configuration classes, one in the main package and one in the test package.
Main
#Configuration
public class DynamoConfiguration {
Test
#TestConfiguration
public class DynamoTestConfiguration {
Unit Test
#ActiveProfiles(profiles = "test")
#ContextConfiguration(classes = {DynamoTestConfiguration.class})
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
#SpringBootTest
public class DynamoClientTest {
Yet, it's still loading DynamoConfiguration and causing failures when I only want the DynamoTestConfiguration to be loaded. How can I ensure that happens?

When using #SpringBootTest, then your application is started, along with any #Configuration classes on the classpath. Spring has no idea that DynamoConfiguration is special and you don't want to load it.
As a way around this, you can use profiles:
#Profile("prod")
#Configuration
public class DynamoConfiguration {
and in your test, add !prod to your #ActiveProfiles:
#ActiveProfiles(profiles = "!prod,test")
#ContextConfiguration(classes = {DynamoTestConfiguration.class})
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
#SpringBootTest
public class DynamoClientTest {
This should avoid that DynamoConfiguration gets loaded in the test.

Related

How to use #componentScan in #springBootTest class

I am creating a test class for my spring application. The main application has following configurations
#SpringBootApplication(scanBasePackages = {"com.graphql.demo"})
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
I need to scan that graphql package for my tests. I tried by added the #ComponentScan in my test class.
#ExtendWith({SpringExtension.class,MockitoExtension.class})
#ComponentScan(basePackages = {"com.graphql.demo"})
#SpringBootTest
public class SampleTestClass {
// my code
}
But it seems it is not reading that graphql packages which I need. How can I scan the base packages in spring boot test?
A single #SpringBootTest should be enough. #SpringBootTest will find the nearest #SpringBootApplication (looking up in the packages hierarchy), and use all of it's configuration.
Make sure that your test resides in the sub-package of the main class (MyApplication) package.
If your MyApplication resides in com.graphql.demo, your test should be in com.graphql.demo.**, otherwise the #SpringBootTest won't find the main class and it's configuration.

Testing Spring Boot Library Modules

I got a multi module project where not every module is actually an application but a lot of them are libs. Those libs are doing the major work and I want to test them where they are implemented. The current dependencies of the libs:
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
In the main source is a class with #Configuration and a single bean:
#Bean public String testString() { return "A Test String"; }
I got 2 test classes:
#RunWith(SpringRunner.class)
#SpringBootTest
#ActiveProfiles({"default", "test"})
public class Test1 {
#Test
public void conextLoaded() {
}
}
-
#RunWith(SpringRunner.class)
#SpringBootTest
#ActiveProfiles({"default", "test"})
public class Test2 {
#Autowired
private String testString;
#Test
public void conextLoaded() {
}
}
The first test works. The second does not. There is not #SpringBootApplication anywhere in that project so in the same package as the Tests I added a test configuration:
#SpringBootConfiguration
#EnableAutoConfiguration
#ComponentScan("com.to.config")
public class LibTestConfiguration {
}
And it does not work. Same for classes that are #Service. They are not in the context. How can I make it behave like a normal Spring boot application without it actually beeing one and load the configs and contexts from the configurations files I need? The default and test profile share most of their properties (for now) and I want them to be loaded like I would start a tomcat.
I switched to JUnit 5 and made it kinda work... So if you want to test Database stuff:
#DataMongoTest
#ExtendWith(SpringExtension.class)
#ActiveProfiles({"default", "test"})
class BasicMongoTest { ... }
Lets you autowire all repositories and mongo template
Initializes with apllicaton.yml config
Does NOT initialize or configure interceptors
Full application context test if you have a class with #SpringBootApplication in your classpath (Can be an empty test main in your test context)
#SpringBootTest
#ExtendWith(SpringExtension.class)
#ActiveProfiles({"default", "test"})
public class FullContextTest { ... }
Initializes the full context with all configs and beans
Should not be done if not necessary as it loads all the application context and kinda defeats the purpose of unit tests to only activate whats needed.
Test only specific components and configs:
#SpringBootTest(classes = {Config1.class, Component1.class})
#EnableConfigurationProperties
#ExtendWith(SpringExtension.class)
#ActiveProfiles({"default", "test"})
public class SpecificComponentsTest { ... }
Initializes the context with only the Config1 and Component1 classes. Component1 and all beans in Config1 can be autowired.

Spring Boot integration tests doesn't read properties files

I would like to create integration test in which Spring Boot will read a value from .properties file using #Value annotation.
But every time I'm running test my assertion fails because Spring is unable to read the value:
org.junit.ComparisonFailure:
Expected :works!
Actual :${test}
My test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {WebTests.ConfigurationClass.class, WebTests.ClassToTest.class})
public class WebTests {
#Configuration
#ActiveProfiles("test")
static class ConfigurationClass {}
#Component
static class ClassToTest{
#Value("${test}")
private String test;
}
#Autowired
private ClassToTest config;
#Test
public void testTransferService() {
Assert.assertEquals(config.test, "works!");
}
}
application-test.properties under src/main/resource package contains:
test=works!
What can be the reason of that behavior and how can I fix it?
Any help highly appreciated.
You should load the application-test.properties using #PropertySource or #TestPropertySource
#RunWith(SpringJUnit4ClassRunner.class)
#TestPropertySource(locations="classpath:application-test.properties")
#ContextConfiguration(classes = {WebTests.ConfigurationClass.class, WebTests.ClassToTest.class})
public class WebTests {
}
for more info: Look into this Override default Spring-Boot application.properties settings in Junit Test
Besides the above marked correct answer, there is another nature way to load application-test.properties: Set your test run "profile" to "test".
Mark your test cases with:
#ActiveProfiles("test")
#RunWith(SpringJUnit4ClassRunner.class)
application-xxxx.properties is a naming convention for properties of different "profile".
This file application-xxxx.properties should be placed in src/main/resources folder.
"Profile" is also useful in bean configuration.

Spring: override beans in integration tests with isolation

I have a problem with overriding beans in integration tests in Spring (with Spock).
Let's say this is my application config:
#EnableWebMvc
#SpringBootApplication
#Configuration
class Main {
#Bean
Race race(Car car) {
// ...
}
#Bean
Car car() {
// ...
}
}
And I have 2 separate integration tests that I want to have to separate Car implementations provided.
#Slf4j
#SpringApplicationConfiguration
class OneIntegrationSpec extends AbstractIntegrationSpec {
#Configuration
#Import(Main.class)
static class Config {
#Bean
Car oneTestCar() {
return new FerrariCar();
}
}
}
#Slf4j
#SpringApplicationConfiguration
class OtherIntegrationSpec extends AbstractIntegrationSpec {
#Configuration
#Import(Main.class)
static class Config {
#Bean
Car otherTestCar() {
return new TeslaCar();
}
}
}
When I run one of these I am getting: NoUniqueBeanDefinitionException cause Spring detects there are multiple car implementations.
How to make test inner class Config with #Configuration annotation being loaded only for that particular test?
I saw the approach with #Profile but that would mean creating separate profiles names for each IntegrationSpec which is a little bit violating a DRY. Is there another approach than #ActiveProfiles?
I'm finding it hard to understand your use-case. Do you have to initialize entire applicationContext to test FerrariCar and TeslaCar? Can't you test them in isolation?
If integration test is the only way to go, you could try excludeFilters in #ComponentScan to disable auto-detecting your test config, as illustrated in https://stackoverflow.com/a/30199808/1553203 . You can then add specific test #Configuration for each Spec/Test by using #Import/#ComponentScan.

Best way to exclude unit test #Configurations in Spring?

In my Spring Boot project, I have a main class annotated with #SpringBootConfiguration. I also have some unit tests that use #SpringApplicationConfiguration that points to an inner class that defines a Spring context for usage in my unit test (using some mocks).
I now want to write an integration test that starts the full context of my application. However, this does not work as it also picks up the Spring contexts that are defined as inner classes in other unit tests.
What would be the best way to avoid that? I did see the exclude and excludeName properties on #SpringBootConfiguration, but I am unsure how to use them.
UPDATE:
Some code to explain the problem more:
My main class:
package com.company.myapp;
#SpringBootApplication
#EnableJpaRepositories
#EnableTransactionManagement
#EntityScan(basePackageClasses = {MyApplication.class, Jsr310JpaConverters.class})
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
I have a unit test for Spring REST Docs:
package com.company.myapp.controller
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration
#WebAppConfiguration
public class SomeControllerDocumentation {
#Rule
public final RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets");
// Some test methods here
// Inner class that defines the context for the unit test
public static class TestConfiguration {
#Bean
public SomeController someController() { return new SomeController(); }
#Bean
public SomeService someService() { return new SomeServiceImpl(); }
#Bean
public SomeRepository someRepository() { return mock(SomeRepository.class);
}
So the unit test uses the context defined in the inner class. Now I want a different test that tests if the "normal" application context of the app starts up:
package com.company.myapp;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(MyApplication.class)
#WebAppConfiguration
public class MyApplicationTest {
#Autowired
private ApplicationContext applicationContext;
#Test
public void whenApplicationStarts_thenContextIsInitialized() {
assertThat(applicationContext).isNotNull();
}
}
This test will now not only wire the stuff it should, but also the beans from the SomeControllerDocumentation.TestConfiguration inner class. This I want to avoid.
You could use profiles: annotate the relevant configuration beans with #Profile("unit-test") and #Profile("integration-test") and inside the tests specify which profile should be active via #ActiveProfiles.
However, it sounds like you could avoid the problem altogether just by reorganising your configuration structure. It's hard to assume anything without seeing any code, though.
Since Spring Boot 1.4, the problem can be avoided by annotation the configuration in the unit tests with #TestConfiguration
I think you talk about #Ignore

Categories

Resources