首页 > 解决方案 > JUnit 5 参数化测试:将 CSVFileSource 与 Enclosed.Class 一起使用

问题描述

我正在尝试使用在同一类中运行参数化和非参数化测试用例

@ExtendWith(MockitoExtension.class)
@RunWith(Enclosed.class)

但不知何故,测试没有运行。我试过csvFileSource没有Enclosed课,效果很好。这是我的测试类骨架的样子:(请帮助)

@ExtendWith(MockitoExtension.class)
@RunWith(Enclosed.class)
public class MyTest {
   static class Base{
   }

   @RunWith(Parameterized.class)
   public static class ParameterizedTests extends Base {
       @ParameterizedTest(name = "testString:{0}")
       @CsvFileSource(resources = "testCases.csv")
       public void test(String testString) {
          ....
       }
   }
}

标签: javajunitjunit5

解决方案


首先,@RunWith是来自 JUnit 4 的注释。运行 JUnit Jupiter 时不需要它@ParameterizedTest。有关详细信息,请参阅https://junit.org/junit5/docs/current/user-guide/#writing-tests-parameterized-tests

接下来,只有非静态嵌套类(即内部类)可以作为@Nested测试类。有关详细信息和推理,请参阅https://junit.org/junit5/docs/current/user-guide/#writing-tests-nested

最小的工作示例:

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

class MyTest {

  class Base {}

  @Nested
  class ParameterizedTests extends Base {
    @ParameterizedTest(name = "testString:{0}")
    @ValueSource(strings = "testCases.csv")
    void test(String testString) {
      System.out.println(testString);
    }
  }
}

推荐阅读