Junit 5 Conditional Test Execution on Operating System Conditions

we can either enable a test case of disable it using @Disable annotation, but junit 5 provides us a way to enable or disable the test case at the run time programatically based on condtions.

package com.example.junit5.sujan;

public class AppleCalculator {
    public int addApple(int appleBag1, int appleBag2) {
        return appleBag1 + appleBag2;
    }
}
package com.example.junit5.sujan;

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.Assertions.assertEquals;
import static org.junit.jupiter.api.condition.OS.*;

class AppleCalculatorTest {

    @Test
    @EnabledOnOs(LINUX)
    void addAppleTestEnabledOnLinux() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertEquals(2, appleCalculator.addApple(1, 1), "1 apple + 1 apple is 2 apple");
    }

    @Test
    @DisabledOnOs(WINDOWS)
    void addAppleTestEnabledOnWindows() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertEquals(2, appleCalculator.addApple(1, 1), "1 apple + 1 apple is 2 apple");
    }

    @Test
    @EnabledOnOs({WINDOWS, MAC})
    void addAppleTestEnabledOnMultipleOs() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertEquals(2, appleCalculator.addApple(1, 1), "1 apple + 1 apple is 2 apple");
    }

    @Test
    @DisabledOnOs({WINDOWS, MAC})
    void addAppleTestDisabledOnMultipleOs() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertEquals(2, appleCalculator.addApple(1, 1), "1 apple + 1 apple is 2 apple");
    }
}
plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
}

 

follow us on