Search code examples
springprofiletestcontainers

@ActiveProfiles in class using Testcontainers but with no @Profile in main code


I currently study this kind of code. In a test class I got something like:

@ActiveProfiles("test")
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = TestcontainersApplication.class, webEnvironment = 
SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ProductRepositoryTest extends ContainersEnvironment {

@Autowired
private ProductRepository productRepository;

So, this is Testcontainers framework. Normally, @ActiveProfiles work with an @Profile in the main code.

For example:

main code ==> @Profile("QA")
test package ==> @ActiveProfiles("QA")

My question is:
How does it come that in my project, I do NOT have any @Profile("test") annotation? How Testcontainers works? Does it make Junit test starting the application with a Spring profile?


Solution

  • So, this is Testcontainers framework. Normally, @ActiveProfiles work with an @Profile in the main code.

    1. @ActiveProfiles doesn't belong to Testcontainers library. It belongs to spring-framework.

    2. The @ActiveProfiles annotation in a test class is instructing Spring to activate the "test" profile when running the tests in this class. This allows you to have specific configurations for your tests, here is some info: (https://www.baeldung.com/spring-tests-override-properties#springProfile). It does not require the presence of a @Profile annotation with the same value in the main code.

    3. How Testcontainers work is a different issue that needs to be considered separately from spring-profiles. But you can start by reading the documentation: https://testcontainers.com/getting-started