18

I have two profiles: dev and default. And I would like to skip some (not all) tests when the active profile is default. Is it possible to mark these tests somehow to do so? Or how can this be achieved? I use springboot. This is my parent test class:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyServiceStarter.class, webEnvironment= SpringBootTest.WebEnvironment.DEFINED_PORT,
        properties = {"flyway.locations=filesystem:../database/h2", "server.port=9100", "spring.profiles.default=dev"})
@Category(IntegrationTest.class)
public abstract class AbstractModuleIntegrationTest { ... }
IKo
  • 3,761
  • 6
  • 26
  • 49

5 Answers5

15

My colleague found a solution: so if you need to annotate separate tests you can use the @IfProfileValue annotation:

@IfProfileValue(name ="spring.profiles.active", value ="default")
    @Test
    public void testSomething() {
        //testing logic
    }

This test will run only when default profile is active

IKo
  • 3,761
  • 6
  • 26
  • 49
5

Yes you can do it.

For example use @ActiveProfiles:

@ActiveProfiles("default")
@RunWith(SpringRunner.class)
@SpringBootTest
public class YourTest {
   //tests
}
Patrick
  • 11,357
  • 14
  • 68
  • 108
  • but this will deactivate all tests in the class. Is it possible to deactivate only several tests? – IKo May 08 '17 at 15:35
  • 2
    This is wrong. "@IfProfileValue" does not decide whether a test runs or not. It only decides which beans definition profiles should be used when the test runs. "@IfProfileValue" should be used as in the accepted answer. For detailed explanation see https://stackoverflow.com/questions/23607489/ifprofilevalue-vs-activeprofiles-in-the-context-of-spring-test/ – Ahmad Abdelghany Apr 23 '20 at 14:44
3

@IfProfileValue only works for JUnit 4. If you're on JUnit 5, as you should be by this time, use @EnabledIf or @DisabledIf.

Example:

@DisabledIf(
    expression = "#{systemProperties['os.name'].toLowerCase().contains('mac')}",
    reason = "Disabled on Mac OS"
)

See the docs for more details.

Abhijit Sarkar
  • 19,114
  • 16
  • 94
  • 178
2

If you want to run the tests from the command line using below:

SPRING_PROFILES_ACTIVE=dev ./gradlew test

and none of the above works for you, you can use below annotation (on a class or single test method):

@DisabledIfEnvironmentVariable(named = "SPRING_PROFILES_ACTIVE", matches = "(dev|default|local)")

The test will be disabled if the spring profile is set to dev or default or local (regular expression)

Fenio
  • 3,269
  • 1
  • 12
  • 24
1

You can use this profile based condition:

@EnabledIf(value = "#{'${spring.profiles.active}' == 'test'}", loadContext = true)
Shtefan
  • 532
  • 6
  • 9