首页 > 解决方案 > 在 @EnabledIf 表达式中找不到变量 junitDisplayName

问题描述

我正在尝试在 gitlab ci 运行器上拆分我的单元测试,因此我想像这样注释我的父测试卡

@EnabledIf("#{systemEnvironment['CI_NODE_INDEX'] == null || junitDisplayName.hashCode() % systemEnvironment['CI_NODE_TOTAL'] == systemEnvironment['CI_NODE_INDEX']}")

但我得到了例外

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'junitDisplayName' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public or not valid?

但文档说应该有这样一个字段:https ://junit.org/junit5/docs/5.3.0/api/org/junit/jupiter/api/condition/EnabledIf.html

标签: javaspringjunitgitlab-ci

解决方案


我尝试了您提供的代码片段来搜索修复,但找不到有效的解决方案。为了规避这个问题,我设置了一个自定义ExecutionCondition,当显示名称包含文本“禁用”时跳过测试(类),并用于@ExtendWith在测试类中包含条件:

DemoApplicationTests

package com.example.demo;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
@ExtendWith(CustomExecutionCondition.class)
//@DisplayName("disabled")
class DemoApplicationTests {

    @Test
    @DisplayName("enabled")
    void shouldBeEnabled() {
    }

    @Test
    @DisplayName("disabled")
    void shouldBeDisabled() {
        throw new IllegalStateException("Should not happen");
    }
}
package com.example.demo;

import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtensionContext;

public class CustomExecutionCondition implements ExecutionCondition {

    @Override
    public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
        String displayName = context.getDisplayName();

//        int ciNodeIndex = Integer.parseInt(System.getProperty("CI_NODE_INDEX"));
//        int ciNodeTotal = Integer.parseInt(System.getProperty("CI_NODE_TOTAL"));

        if (displayName != null && displayName.contains("disabled")) {
            return ConditionEvaluationResult.disabled("Test '" + displayName + "' is disabled");
        }

        return ConditionEvaluationResult.enabled("Test '" + displayName + "' is enabled");
    }
}

我省略了系统属性和哈希码评估以简化示例。条件评估3次;测试班一次,测试方法两次。如果类级别评估返回 false,则跳过该类中的所有测试方法。


推荐阅读