java - 如何对两种不同的文件格式运行单元测试?
问题描述
我需要测试一个与 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
我不想只是复制和粘贴整个类并只更改一个变量,但我不知道如何通过使类抽象或其他东西来做到这一点。测试在两个文件上的工作方式相同(就像我的数据库代码一样),并且两个文件都包含完全相同的测试数据。
解决方案
您可以使用jUnit5 参数化测试:注释的测试将为“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
}
推荐阅读
- instagram-api - Instagram 的用户媒体 API 返回丢失的视频 URL
- text-to-speech - 尝试获取 Microsoft Text-to-speech 上的语音列表时出现 404 错误
- ios - Swift 泛型 - 无法将值转换为类型
- reactjs - 为什么我不能使用全局空间中的 react 和 express 库(通过 npm i -g pkgName 安装)但我可以使用全局空间中的 react-scripts
- sql - postgres/Sequelize:如果属性值匹配,则编辑 jsonb 数组中的对象
- mysql - 如果没有未来记录,则选择过去的记录,否则选择第一个未来记录
- javascript - 在打字稿中输入路线(反应导航)
- javascript - 我的按钮文本总是显示在我为其设置的填充之外?
- java - Callbable 语句 JDBC 性能问题
- linux - ftp:登录到服务器,自动更改远程目录,然后带来用户输入?