在 JUnit4 中使用参数化测试时,有没有办法设置我自己的自定义测试用例名称?

我想更改默认值 — [Test class].runTest[n] ——做一些有意义的事情。

有帮助吗?

解决方案

该功能已成为 JUnit 4.11.

要使用更改参数化测试的名称,您可以说:

@Parameters(name="namestring")

namestring 是一个字符串,可以有以下特殊占位符:

  • {index} - 这组参数的索引。默认 namestring{index}.
  • {0} - 此测试调用中的第一个参数值。
  • {1} - 第二个参数值
  • 等等

测试的最终名称将是测试方法的名称,后跟 namestring 括号内,如下所示。

例如(改编自单元测试 Parameterized 注解):

@RunWith(Parameterized.class)
static public class FibonacciTest {

    @Parameters( name = "{index}: fib({0})={1}" )
    public static Iterable<Object[]> data() {
        return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
                { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
    }

    private final int fInput;
    private final int fExpected;

    public FibonacciTest(int input, int expected) {
        fInput= input;
        fExpected= expected;
    }

    @Test
    public void testFib() {
        assertEquals(fExpected, fib(fInput));
    }

    private int fib(int x) {
        // TODO: actually calculate Fibonacci numbers
        return 0;
    }
}

会给出像这样的名字 testFib[1: fib(1)=1]testFib[4: fib(4)=3]. 。(这 testFib 名称的一部分是方法名称 @Test).

其他提示

综观JUnit的4.5,它的转轮显然不支持,因为该逻辑被掩埋的私有类内的参数化类的内部。你不能使用JUnit的参数亚军,而是创建自己这将了解名称的概念(这导致了如何设置一个名字......这个问题)。

从一个JUnit的角度来看,这将是很好的,如果不是(或除了)只是路过一个增量,它们会通过逗号分隔的参数。 TestNG的做到这一点。如果该功能对你很重要,你可以在www.junit.org引用的雅虎邮件列表中发表评论。

我最近在使用 JUnit 4.3.1 时遇到了同样的问题。我实现了一个扩展 Parameterized 的新类,称为 LabelledParameterized。它已使用 JUnit 4.3.1、4.4 和 4.5 进行了测试。它使用 @Parameters 方法中每个参数数组的第一个参数的字符串表示形式重建 Description 实例。您可以在以下位置查看此代码:

http://code.google.com/p/migen/source/browse/trunk/java/src/.../LabelledParameterized.java?r=3789

及其使用示例位于:

http://code.google.com/p/migen/source/browse/trunk/java/src/.../ServerBuilderTest.java?r=3789

测试描述在 Eclipse 中的格式很好,这正是我想要的,因为这使得失败的测试更容易找到!我可能会在接下来的几天/几周内进一步完善和记录课程。放下“?”如果您想要出血边缘,则为URL的一部分。:-)

要使用它,您所要做的就是复制该类(GPL v3),并将 @RunWith(Parameterized.class) 更改为 @RunWith(LabelledParameterized.class) 假设参数列表的第一个元素是一个合理的标签。

我不知道 JUnit 的任何后续版本是否解决了这个问题,但即使解决了,我也无法更新 JUnit,因为我的所有合作开发人员也必须更新,而且我们的优先级高于重新工具。因此,类中的工作可由多个版本的 JUnit 进行编译。


笔记: 有一些反射 jiggery-pokery,因此它可以跨上面列出的不同 JUnit 版本运行。可以找到专门针对 JUnit 4.3.1 的版本 这里 并且,对于 JUnit 4.4 和 4.5, 这里.

通过Parameterized作为一种模式,我写我自己的自定义测试跑步/套件 - 只花了约半小时。这是略有不同darrenp的LabelledParameterized的,因为它可以让你指定一个名称,明确而不是依赖于第一个参数的toString()

它还因为我讨厌阵列不使用阵列。 :)

public class PolySuite extends Suite {

  // //////////////////////////////
  // Public helper interfaces

  /**
   * Annotation for a method which returns a {@link Configuration}
   * to be injected into the test class constructor
   */
  @Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.METHOD)
  public static @interface Config {
  }

  public static interface Configuration {
    int size();
    Object getTestValue(int index);
    String getTestName(int index);
  }

  // //////////////////////////////
  // Fields

  private final List<Runner> runners;

  // //////////////////////////////
  // Constructor

  /**
   * Only called reflectively. Do not use programmatically.
   * @param c the test class
   * @throws Throwable if something bad happens
   */
  public PolySuite(Class<?> c) throws Throwable {
    super(c, Collections.<Runner>emptyList());
    TestClass testClass = getTestClass();
    Class<?> jTestClass = testClass.getJavaClass();
    Configuration configuration = getConfiguration(testClass);
    List<Runner> runners = new ArrayList<Runner>();
    for (int i = 0, size = configuration.size(); i < size; i++) {
      SingleRunner runner = new SingleRunner(jTestClass, configuration.getTestValue(i), configuration.getTestName(i));
      runners.add(runner);
    }
    this.runners = runners;
  }

  // //////////////////////////////
  // Overrides

  @Override
  protected List<Runner> getChildren() {
    return runners;
  }

  // //////////////////////////////
  // Private

  private Configuration getConfiguration(TestClass testClass) throws Throwable {
    return (Configuration) getConfigMethod(testClass).invokeExplosively(null);
  }

  private FrameworkMethod getConfigMethod(TestClass testClass) {
    List<FrameworkMethod> methods = testClass.getAnnotatedMethods(Config.class);
    if (methods.isEmpty()) {
      throw new IllegalStateException("@" + Config.class.getSimpleName() + " method not found");
    }
    if (methods.size() > 1) {
      throw new IllegalStateException("Too many @" + Config.class.getSimpleName() + " methods");
    }
    FrameworkMethod method = methods.get(0);
    int modifiers = method.getMethod().getModifiers();
    if (!(Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
      throw new IllegalStateException("@" + Config.class.getSimpleName() + " method \"" + method.getName() + "\" must be public static");
    }
    return method;
  }

  // //////////////////////////////
  // Helper classes

  private static class SingleRunner extends BlockJUnit4ClassRunner {

    private final Object testVal;
    private final String testName;

    SingleRunner(Class<?> testClass, Object testVal, String testName) throws InitializationError {
      super(testClass);
      this.testVal = testVal;
      this.testName = testName;
    }

    @Override
    protected Object createTest() throws Exception {
      return getTestClass().getOnlyConstructor().newInstance(testVal);
    }

    @Override
    protected String getName() {
      return testName;
    }

    @Override
    protected String testName(FrameworkMethod method) {
      return testName + ": " + method.getName();
    }

    @Override
    protected void validateConstructor(List<Throwable> errors) {
      validateOnlyOneConstructor(errors);
    }

    @Override
    protected Statement classBlock(RunNotifier notifier) {
      return childrenInvoker(notifier);
    }
  }
}

和的示例:

@RunWith(PolySuite.class)
public class PolySuiteExample {

  // //////////////////////////////
  // Fixture

  @Config
  public static Configuration getConfig() {
    return new Configuration() {
      @Override
      public int size() {
        return 10;
      }

      @Override
      public Integer getTestValue(int index) {
        return index * 2;
      }

      @Override
      public String getTestName(int index) {
        return "test" + index;
      }
    };
  }

  // //////////////////////////////
  // Fields

  private final int testVal;

  // //////////////////////////////
  // Constructor

  public PolySuiteExample(int testVal) {
    this.testVal = testVal;
  }

  // //////////////////////////////
  // Test

  @Ignore
  @Test
  public void odd() {
    assertFalse(testVal % 2 == 0);
  }

  @Test
  public void even() {
    assertTrue(testVal % 2 == 0);
  }

}

从junit4.8.2,您可以创建自己的MyParameterized类通过简单地复制参数类。改变TestClassRunnerForParameters所述的getName()和测试名()方法。

您也可以试试JUnitParams: http://code.google.com/p/junitparams /

可以创建等的方法

@Test
public void name() {
    Assert.assertEquals("", inboundFileName);
}

虽然我不使用它,将是有益的所有时间找出究竟哪些测试号143。

我广泛使用的断言和朋友静态导入的,所以很容易让我重新认识了断言:

private <T> void assertThat(final T actual, final Matcher<T> expected) {
    Assert.assertThat(editThisToDisplaySomethingForYourDatum, actual, expected);
}

例如,你可以“名称”字段添加到您的测试类,在构造函数初始化,并显示在测试失败。只是把它作为你的参数数组为每个测试的第一要素。这也有助于标记数据:

public ExampleTest(final String testLabel, final int one, final int two) {
    this.testLabel = testLabel;
    // ...
}

@Parameters
public static Collection<Object[]> data() {
    return asList(new Object[][]{
        {"first test", 3, 4},
        {"second test", 5, 6}
    });
}

这都不是为我工作,所以我得到了参数的来源和修改它创建一个新的测试运行。我没有太大变化,但工程!

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Assert;
import org.junit.internal.runners.ClassRoadie;
import org.junit.internal.runners.CompositeRunner;
import org.junit.internal.runners.InitializationError;
import org.junit.internal.runners.JUnit4ClassRunner;
import org.junit.internal.runners.MethodValidator;
import org.junit.internal.runners.TestClass;
import org.junit.runner.notification.RunNotifier;

public class LabelledParameterized extends CompositeRunner {
static class TestClassRunnerForParameters extends JUnit4ClassRunner {
    private final Object[] fParameters;

    private final String fParameterFirstValue;

    private final Constructor<?> fConstructor;

    TestClassRunnerForParameters(TestClass testClass, Object[] parameters, int i) throws InitializationError {
        super(testClass.getJavaClass()); // todo
        fParameters = parameters;
        if (parameters != null) {
            fParameterFirstValue = Arrays.asList(parameters).toString();
        } else {
            fParameterFirstValue = String.valueOf(i);
        }
        fConstructor = getOnlyConstructor();
    }

    @Override
    protected Object createTest() throws Exception {
        return fConstructor.newInstance(fParameters);
    }

    @Override
    protected String getName() {
        return String.format("%s", fParameterFirstValue);
    }

    @Override
    protected String testName(final Method method) {
        return String.format("%s%s", method.getName(), fParameterFirstValue);
    }

    private Constructor<?> getOnlyConstructor() {
        Constructor<?>[] constructors = getTestClass().getJavaClass().getConstructors();
        Assert.assertEquals(1, constructors.length);
        return constructors[0];
    }

    @Override
    protected void validate() throws InitializationError {
        // do nothing: validated before.
    }

    @Override
    public void run(RunNotifier notifier) {
        runMethods(notifier);
    }
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public static @interface Parameters {
}

private final TestClass fTestClass;

public LabelledParameterized(Class<?> klass) throws Exception {
    super(klass.getName());
    fTestClass = new TestClass(klass);

    MethodValidator methodValidator = new MethodValidator(fTestClass);
    methodValidator.validateStaticMethods();
    methodValidator.validateInstanceMethods();
    methodValidator.assertValid();

    int i = 0;
    for (final Object each : getParametersList()) {
        if (each instanceof Object[])
            add(new TestClassRunnerForParameters(fTestClass, (Object[]) each, i++));
        else
            throw new Exception(String.format("%s.%s() must return a Collection of arrays.", fTestClass.getName(), getParametersMethod().getName()));
    }
}

@Override
public void run(final RunNotifier notifier) {
    new ClassRoadie(notifier, fTestClass, getDescription(), new Runnable() {
        public void run() {
            runChildren(notifier);
        }
    }).runProtected();
}

private Collection<?> getParametersList() throws IllegalAccessException, InvocationTargetException, Exception {
    return (Collection<?>) getParametersMethod().invoke(null);
}

private Method getParametersMethod() throws Exception {
    List<Method> methods = fTestClass.getAnnotatedMethods(Parameters.class);
    for (Method each : methods) {
        int modifiers = each.getModifiers();
        if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))
            return each;
    }

    throw new Exception("No public static parameters method on class " + getName());
}

public static Collection<Object[]> eachOne(Object... params) {
    List<Object[]> results = new ArrayList<Object[]>();
    for (Object param : params)
        results.add(new Object[] { param });
    return results;
}
}

一个解决方法是捕捉和巢所有将Throwable与含有有关参数的所有的信息的自定义消息的新的Throwable。该消息将出现在堆栈跟踪。 的这适用每当一个测试为所有断言,错误和异常失败,因为它们的Throwable的所有子类。

我的代码看起来是这样的:

@RunWith(Parameterized.class)
public class ParameterizedTest {

    int parameter;

    public ParameterizedTest(int parameter) {
        super();
        this.parameter = parameter;
    }

    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] { {1}, {2} });
    }

    @Test
    public void test() throws Throwable {
        try {
            assertTrue(parameter%2==0);
        }
        catch(Throwable thrown) {
            throw new Throwable("parameter="+parameter, thrown);
        }
    }

}

失败的测试的堆栈跟踪是:

java.lang.Throwable: parameter=1
    at sample.ParameterizedTest.test(ParameterizedTest.java:34)
Caused by: java.lang.AssertionError
    at org.junit.Assert.fail(Assert.java:92)
    at org.junit.Assert.assertTrue(Assert.java:43)
    at org.junit.Assert.assertTrue(Assert.java:54)
    at sample.ParameterizedTest.test(ParameterizedTest.java:31)
    ... 31 more

查核JUnitParams如dsaff提到的,使用蚂蚁作品构建在HTML报告的参数化测试方法的描述。

这是试图LabelledParameterized和发现它,虽然它与Eclipse的工作不会与蚂蚁只要HTML报告涉及工作岗位。

干杯,

由于访问的参数(例如用"{0}"总是返回toString()表示,一个解决办法是使一个匿名的实现和在每种情况下覆盖toString()例如:

public static Iterable<? extends Object> data() {
    return Arrays.asList(
        new MyObject(myParams...) {public String toString(){return "my custom test name";}},
        new MyObject(myParams...) {public String toString(){return "my other custom test name";}},
        //etc...
    );
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top