Monday 5 July 2021

Junit5: @EnabledIfEnvironmentVariable, @DisabledIfEnvironmentVariable: Enable or disable based on environment variable

@EnabledIfEnvironmentVariable  is used to signal that the annotated test class or test method is only enabled if the value of the specified environment variable matches the specified regular expression.

 

Example

@Test
@EnabledIfEnvironmentVariable(named = "env", matches = "staging")
void onlyOnStagingEnvt() {
  assertTrue(true);
}

 

@DisabledIfEnvironmentVariable annotation is used to signal that the annotated test class or test method is disabled if the value of the specified environment variable matches the specified regular expression.

 

Example

@Test
@DisabledIfEnvironmentVariable(named = "env", matches = "staging")
void notOnStagingEnvt() {
  assertTrue(true);
}

 

EnvironmentVariableTest.java

package com.sample.app;

import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;

public class EnvironmentVariableTest {

	@Test
	@EnabledIfEnvironmentVariable(named = "env", matches = "staging")
	void onlyOnStagingEnvt() {
		assertTrue(true);
	}

	@Test
	@DisabledIfEnvironmentVariable(named = "env", matches = "staging")
	void notOnStagingEnvt() {
		assertTrue(true);
	}
	
}

  Run above test class, you will observe that ‘onlyOnStagingEnvt’ test method gets skipped.

 


 

Let’s pass the environment variable ‘env’ by setting to ‘staging’ and re run the test.

 

 


Right click on 'EnvironmentVariableTest' -> Run As -> Run Configurations…

 


Go to ‘Environment’ tab, and add the environment variable ‘env’ and set it to the value ‘staging’.

 

Click on Run button.


You can observe that ‘notOnStagingEnvt()’ test method is disabled.

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment