有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我需要测试一个与YAML和JSON文件格式相同的系统。我为数据库后端编写了一系列单元测试,但我想在这两种格式上运行它们。我需要改变的只是为测试提供的路径。我正在使用Java8和org。朱尼特。朱庇特

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

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


共 (1) 个答案

  1. # 1 楼答案

    您可以使用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
        }