在参数化测试类中排除非参数测试

use*_*516 54 java junit parameterized

JUnit中是否有任何注释可以在参数化测试类中排除非参数测试?

Mat*_*son 55

JUnit 5

从Junit 5.0.0开始,您现在可以使用注释来测试您的测试方法@ParameterizedTest.所以不需要内部课程.除了ValueSource之外,还有很多方法可以为参数化测试提供参数,如下所示.有关详细信息,请参阅官方junit用户指南:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

public class ComponentTest {

    @ParameterizedTest
    @ValueSource(strings = { "racecar", "radar", "able was I ere I saw elba" })
    public void testCaseUsingParams(String candidate) throws Exception {
    }

    @Test
    public void testCaseWithoutParams() throws Exception {
    }
}
Run Code Online (Sandbox Code Playgroud)

JUnit 4

如果您仍在使用Junit 4(我使用v4.8.2测试过),您可以将Enclosed runner与内部类和Parameterized runner一起使用:

import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Enclosed.class)
public class ComponentTest {

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

        @Parameters
        ...

        @Test
        public void testCaseUsingParams() throws Exception {
        }
    }

    public static class ComponentSingleTests {

        @Test
        public void testCaseWithoutParams() throws Exception {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不错的解决方案,但是,它运行了两次测试!Enclosure.class 是 Suite.class 的扩展,它会导致所有 Suite 运行两次,而不是本例中的参数数量。 (3认同)
  • 很好而且清晰的解决方案,您可以在同一模块中实现参数化和单个测试之间的良好分离. (2认同)

Ama*_*icA 12

刚刚发现可以使用JUnitParams.我现在转换了我的一个测试来使用它并且它工作得非常漂亮.


Jea*_*sky 6

不是.最佳做法是将这些非参数化测试移动到不同的类(.java文件)

  • 一个模块=一个测试类是这种做法与之相冲突的另一个最佳实践.它更像是一种解决方法而不是最佳实践. (25认同)
  • @scubbo我不明白为什么在两个不同的班级进行测试是一个坏主意。即使没有参数化测试,我也已经为某些类做到了这一点。例如 Foo_SecurityTest、Foo_BusinessLogicTest。 (2认同)