'Using @TestConfiguration doesn't work as Context for @SpringBootTest

I've written an integration test that uses @SpringBootTest annotation. Since my app has many beans, I want to load in the integration test only the beans that are relevant for the test. For this, I used the @ContextConfiguration annotation.

However, it seems that the context loads also other beans and I'm not sure why.

My beans :

@AllArgsConstructor
@NoArgsConstructor
public class A {
    private String name = "";
}

@Component
@RequiredArgsConstructor
public class B {
    private final  A a;

    public void doSomething(){}
}

@Component
@AllArgsConstructor
public class C {
    private String cname;
}

My configuration class :

@Configuration
public class DMConfiguration {

    @Bean
    public A getA(){
        return new A("just-name");
    }
}

My integration test consist of 2 parts :

TestConfig:

@TestConfiguration
@Import(DMConfiguration.class)
public class DMTestConfiguration {

    @Bean
    public B getB(A a){
        return new B(a);
    }
}

Notice that I import the config from my main code and I don't want to overwrite them.

My test :

@SpringBootTest
@ContextConfiguration(classes=DMTestConfiguration.class)
public class MyTest {

    @Autowired
    private B b;

    @Test
    public void testB(){
        b.doSomething();
    }

}

The test fails because Spring can't initialize the bean C (missing bean of type String for the property cname) :

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'c' defined in file dm/C.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

As you can see, Spring tries to load also beans outside of the context I configured. I tried changing the @TestConfiguration annotation to @Configuration and everything worked as expected ! I don't want to do that because then it means that other integration tests will load this configuration even if they don't need the beans inside (I prefer also not to use profiles in testing).



Solution 1:[1]

Try to replace @ContextConfiguration(classes=DMTestConfiguration.class) with @Import(DMTestConfiguration.class)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael Gantman