Monday 28 June 2021

Junit5: Conditional Test Execution

Junit5 provides a way to enable/disable tests based on certain conditions programmatically. 'org.junit.jupiter.api.condition' package provides built in annotation based conditions for enabling or disabling tests in JUnit Jupiter.

 

For example, annotations @EnabledOnOs and @DisabledOnOs used to enable and disable the test methods depends on operating system.

 

Example

@Test
@EnabledOnOs(MAC)
void onlyOnMacOs() {
  System.out.println("This test executes only on MAC");
}

 

Find the below working application.

 

ConditionsDemo.java

package com.sample.app.conditions;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.EnabledOnOs;

import static org.junit.jupiter.api.condition.OS.*;

public class ConditionsDemo {
  @Test
  @EnabledOnOs(MAC)
  void onlyOnMacOs() {
    System.out.println("This test executes only on MAC");
  }

  @Test
  @EnabledOnOs(WINDOWS)
  void onlyOnWindows() {
    System.out.println("This test executes only on WINDOWS");
  }

  @Test
  @EnabledOnOs({ LINUX, MAC })
  void onLinuxOrMac() {
    System.out.println("This test executes only on MAC and Linux");
  }

  @Test
  @DisabledOnOs(WINDOWS)
  void notOnWindows() {
    System.out.println("This test do not executes on Windows");
  }
}

 

Run above application, you will observe test cases gets executed based on your operating system.

 

For example, When I ran this test class in MAC operating system I observed ‘onlyOnWindows’ test gets skipped.

 


 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment