我如何 运行 对两种不同的文件格式进行单元测试?

How do I run unit tests on two different file formats?

我需要测试一个与 YAML 和 JSON 文件格式相同的系统。我为数据库后端编写了一堆单元测试,但我想在两种格式上 运行 它们。我需要更改的只是为测试提供的路径。我正在使用 Java 8 和 org.junit.jupiter.

import static org.junit.jupiter.api.Assertions.*;

public class DatabaseTests {

    //Need to re-test for "src\test\java\backend\database\testDB.yaml"
    private final static String TEST_DB_JSON = "src\test\java\backend\database\testDB.json";

    private static byte[] testFileState;

    @BeforeAll
    static void setUp() {
        try {
            testFileState = Files.readAllBytes(Paths.get(TEST_DB_JSON));
            reloadDatabase();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @AfterEach
    void resetFile() {
        try (FileOutputStream fos = new FileOutputStream(TEST_DB_JSON)) {
            fos.write(testFileState);
        } catch (IOException e) {
            e.printStackTrace();
        }
        reloadDatabase();
    }

    //A bunch of unit tests

我不想只复制和粘贴整个 class 并只更改一个变量,但我不知道如何通过使 class 抽象或其他方式来做到这一点。测试在两个文件上的工作方式相同(我的数据库代码也是如此)并且两个文件包含完全相同的测试数据。

您可以使用 jUnit5 Parametrized Tests:注释的测试将为 "MethodSource"

返回的每个值 运行
    private final static String TEST_DB_JSON = "src\test\java\backend\database\testDB.json";
    private final static String TEST_DB_YAML = "src\test\java\backend\database\testDB.yaml";

    private List<byte[]> inputFiles() {
        byte[] jsonTestFileState;
        byte[] yamlTestFileState;
        try {
            jsonTestFileState = Files.readAllBytes(Paths.get(TEST_DB_JSON));
            yamlTestFileState = Files.readAllBytes(Paths.get(TEST_DB_YAML));
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
        return Arrays.asList(jsonTestFileState, yamlTestFileState);
    }

    @ParameterizedTest
    @MethodSource("inputFiles")
    void shouldDoSomething(byte[] testFileState) {
       // This method will be called twice: the 1st time with
       // jsonTestFileState as the value of the argument 
       // and the second time with yamlTestFileState
    }