Spring-boot utilizes Spring profiles which allow for instance to have separate config for different environments. One way I use this feature is to configure test database to be used by integration tests. I wonder however is it necessary to create my own profile 'test' and explicitly activate this profile in each test file? Right now I do it in the following way:
Create application-test.properties inside src/main/resources
Write test specific config there (just the database name for now)
In every test file include:
@ActiveProfiles("test")
Is there a smarter / more concise way? For instance a default test profile?
โ07-31-2022 10:40 PM
As far as I know there is nothing directly addressing your request - but I can suggest a proposal that could help:
You could use your own test annotation that is a meta annotation comprising @SpringBootTest and @ActiveProfiles("test"). So you still need the dedicated profile but avoid scattering the profile definition across all your test.
This annotation will default to the profile test and you can override the profile using the meta annotation.
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @SpringBootTest @ActiveProfiles public @interface MyApplicationTest { @AliasFor(annotation = ActiveProfiles.class, attribute = "profiles") String[] activeProfiles() default {"test"}; }
โ08-05-2022 12:11 AM
Another way to do this is to define a base (abstract) test class that your actual test classes will extend :
@RunWith(SpringRunner.class) @SpringBootTest() @ActiveProfiles("staging") public abstract class BaseIntegrationTest { }
Concrete test :
public class SampleSearchServiceTest extends BaseIntegrationTest{ @Inject private SampleSearchService service; @Test public void shouldInjectService(){ assertThat(this.service).isNotNull(); } }
This allows you to extract more than just the @ActiveProfiles annotation. You could also imagine more specialized base classes for different kinds of integration tests, e.g. data access layer vs service layer, or for functional specialties (common @Before or @After methods etc).
Along with the approach below, you can also add config to src/test/resources/config/application.yml
src/ โโโ main/ โ โโโ java/ โ โ โโโ ... โ โโโ resources/ โ โโโ application.yml <- default properties, always loaded โโโ test/ โโโ java/ โ โโโ ... โโโ resources/ โโโ config/ โโโ application.yml <- test properties, will override the defaults
https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-confi.../omegleshagle
โ08-25-2022 04:34 AM