【问题标题】:JUnit 5 @ParameterizedTest with using class as @ValueSource [duplicate]JUnit 5 @ParameterizedTest 使用类作为@ValueSource [重复]
【发布时间】:2019-06-24 12:42:28
【问题描述】:

我想用@ValueSource 做一个ParameterizedTest,我已经阅读了很多教程,包括Guide to JUnit 5 Parameterized Tests

/**
 * The {@link Class} values to use as sources of arguments; must not be empty.
 *
 * @since 5.1
 */
Class<?>[] classes() default {};

所以我尝试了以下方法:

@ParameterizedTest
@ValueSource(classes = {new Mandator("0052", "123456", 79)})
void testCalculateMandateI(Mandator value) {

     //code using Mandator here
}

强制类:

 public class Mandator {

    private String creditorPrefix;
    private String retailerCode;
    private int mandateIdSequence;

    public Mandator(final String creditorPrefix, final String retailerCode, final int mandateIdSequence) {
        this.creditorPrefix = creditorPrefix;
        this.retailerCode = retailerCode;
        this.mandateIdSequence = mandateIdSequence;
    }

    public String getCreditorPrefix() {
        return creditorPrefix;
    }

    public String getRetailerCode() {
        return retailerCode;
    }

    public int getMandateIdSequence() {
        return mandateIdSequence;
    }
}

但我从 IntelliJ 收到以下错误,悬停在 @ValueSource 上方:

属性值必须是常数

我在这里做错了什么?我错过了什么?

【问题讨论】:

  • 第一个解释了如何将 JUnit 与源代码一起使用。其他人解释了错误的原因,“属性值必须是常量”,您收到了。它们都是相关的。

标签: java junit5 parameterized


【解决方案1】:

这不是关于 JUnit,而是关于 Java 语法。

注解的参数中不可能创建新对象。

注解元素的类型是以下之一:

  • List 基本类型(int、short、long、byte、char、double、float 或 boolean)
  • 字符串
  • 类(带有可选的类型参数,例如 Class)
  • 枚举类型
  • 注释类型
  • 上述类型的数组(数组数组不是合法的元素类型)

如果您想从创建的对象中提供值,请考虑使用类似的方法作为一种可能的解决方案:

@ParameterizedTest
@MethodSource("generator")
void testCalculateMandateI(Mandator value, boolean expected)

// and then somewhere in this test class  
private static Stream<Arguments> generator() {

 return Stream.of(
   Arguments.of(new Mandator(..), true),
   Arguments.of(new Mandator(..), false));
}

【讨论】:

  • 太好了,我只是不明白你在Arguments.of()上添加的truefalse是什么
  • 这应该是预期的结果。毕竟给定不同的参数,您期望验证不同的结果。它不一定是布尔值,只要是您可以验证的值即可。
猜你喜欢
  • 2018-10-02
  • 2018-12-21
  • 2020-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-03
  • 1970-01-01
相关资源
最近更新 更多