Prevent tests from running with specific spring profile

Viewed 816

I have some integration tests that create/delete entries in my database. The problem is if I run the tests with

spring.profiles.active=prod

my production database gets deleted (as the tests clear the database). Is there any way to prevent tests from running on this specific spring profile?

I have seen this thread: How to prevent running tests when specific spring profile is active? but there was no useful answer.

Thank you

3 Answers

There could be multiple solution to your problem.

  1. Using in-memory databases like H2 for Sql and flapdoodle for no-sql for running tests. **preferred way
  2. Create a separate properties file with clone of spring properties. Just change the database properties/spring profile or other things. Use this properties file with @testpropertysource on test class.
  3. Use @dirtiescontext on tests to create/delete impacted rows only.
  4. Another thing you can do is create stud classes your database layer to mock operations.

I was able to resolve the problem following this comment: https://stackoverflow.com/a/32892291/8679100. The solution is not perfect, as I need to verify if the prod profile is active in @BeforeAll and @AfterAll, but it does work. Furthermore, System.getProperty("spring.profiles.active", "");didn't actually work, butArrays.stream(environment.getActiveProfiles()).anyMatch(env -> (env.equalsIgnoreCase("prod")))``` did

You can use @IfProfileValue annotation to disable the test. it's not directly depend on the spring profile, but you can easily use config file to set the value you want based on the spring profile.

Having said that - it sounds very risky to run tests that delete entries from the db (or any other db transaction) on production DB. I support what @Sachin suggested above - run your test on tests environment, not production

Related