简体   繁体   中英

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

I need to test a system that works identically with YAML and JSON file formats. I wrote up a bunch of unit tests for the database backend but I want to run them on both formats. All I need to change is the path provided for the tests. I'm using Java 8 and 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

I dont want to just copy and paste the whole class and change just one variable but I cant figure out how to do this by making the class abstract or something. The tests work identically on both files (as does my database code) and both files contain the same exact same test data.

You can use jUnit5 Parametrized Tests : the tests annotated will be run for each value returned by the "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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM