java - junit5 创建临时文件
问题描述
我用 junit 5 编写了一个单元测试,测试一些我需要一个文件夹和一些文件的文件系统逻辑。我在文档中找到了TempDir注释,并用它创建了一个文件夹,我在其中保存了一些文件。就像是:
@TempDir
static Path tempDir;
static Path tempFile;
// ...
@BeforeAll
public static void init() throws IOException {
tempFile = Path.of(tempDir.toFile().getAbsolutePath(), "test.txt");
if (!tempFile.toFile().createNewFile()) {
throw new IllegalStateException("Could not create file " + tempFile.toFile().getAbsolutePath());
}
// ...
}
在 junit4 中,可以使用TemporaryFolder#newFile(String)。这似乎在junit5中不存在。
我错过了什么吗?它可以工作,所以我想这很好,但我想知道是否有一种更简洁的方法可以直接使用 junit 5 api 创建一个新文件。
解决方案
如果您使用Files
. 这是一个更简洁的定义tempFile
,应该提供类似的错误处理:
@TempDir
static Path tempDir;
static Path tempFile;
@BeforeAll
public static void init() throws IOException {
tempFile = Files.createFile(tempDir.resolve("test.txt"));
}
确保您拥有最新版本的 JUNIT5。下面的测试应该通过,但在一些旧版本的 JUNIT 中失败,这些旧版本不会生成@TempDir
for 字段tempDir
和的唯一值mydir
:
@Test void helloworld(@TempDir Path mydir) {
System.out.println("helloworld() tempDir="+tempDir+" mydir="+mydir);
assertFalse(Objects.equals(tempDir, mydir));
}
推荐阅读
- jquery - 修复 ajax 问题并验证插件
- ios - 如何使用 UIPreviewParameters 将文本范围指定为 UIContextMenuInteraction 的突出显示预览而不隐藏视图的其余部分?
- android - Flutter 如何从 CupertinoTimerPicker 返回数据?
- python - macOS 脚本编辑器 - AttributeError:模块“枚举”没有属性“IntFlag”
- javascript - 'RangeError: 无效的时间值'
- c# - 无法隐式转换类型 List
列出 错误 - spring-boot - 控制不来查看 i。春季启动中的 JSP /HTML
- python - 烧瓶并使用日期时间处理 Zeep 响应
- java - 如何使用 PageFactory.initElement(driver, this) 的索引号来识别 DOM 中的两个相同元素?
- javascript - Google oauth2 日历 API 登录事件 gapi.auth2.getAuthInstance().isSignedIn.listen() 未在 Safari 中触发