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

问题描述 投票:0回答:1

我需要测试与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

我不想只复制并粘贴整个类并仅更改一个变量,但是我无法弄清楚如何通过使类抽象化或其他方式来做到这一点。测试在两个文件上都相同(与我的数据库代码一样),并且两个文件包含完全相同的测试数据。

java unit-testing testing junit abstract-class
1个回答
0
投票

您可以使用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
    }
© www.soinside.com 2019 - 2024. All rights reserved.