Hamcrest 文件匹配器简介
Contents
1. 概述
在本教程中,我们将讨论 Hamcrest 文件匹配器。
在之前的使用 Hamcrest 进行测试的 文章中,我们一般讨论了 Hamcrest 匹配器。在接下来的部分中,我们将只关注File匹配器。
2. Maven配置
首先,我们需要在pom.xml中添加以下依赖项:
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>2.0.0.0</version>
<scope>test</scope>
</dependency>
可以从 Maven Central 下载最新版本的java-hamcrest 。
让我们继续探索 HamcrestFile匹配器。
3. 文件属性
Hamcrest 提供了几个匹配器来验证常用的File属性。
让我们看看如何使用aFileNamed()结合string匹配器来验证File名:
@Test
public void whenVerifyingFileName_thenCorrect() {
File file = new File("src/test/resources/test1.in");
assertThat(file, aFileNamed(equalToIgnoringCase("test1.in")));
}
我们还可以评估文件路径——再次结合字符串匹配器:
@Test
public void whenVerifyingFilePath_thenCorrect() {
File file = new File("src/test/resources/test1.in");
assertThat(file, aFileWithCanonicalPath(containsString("src/test/resources")));
assertThat(file, aFileWithAbsolutePath(containsString("src/test/resources")));
}
让我们也看看文件的大小——以字节为单位:
@Test
public void whenVerifyingFileSize_thenCorrect() {
File file = new File("src/test/resources/test1.in");
assertThat(file, aFileWithSize(11));
assertThat(file, aFileWithSize(greaterThan(1L)));;
}
最后,我们可以检查一个File是否可读可写:
@Test
public void whenVerifyingFileIsReadableAndWritable_thenCorrect() {
File file = new File("src/test/resources/test1.in");
assertThat(file, aReadableFile());
assertThat(file, aWritableFile());
}
4. 现有文件匹配器
如果我们想验证File或目录是否存在,我们可以使用*anExistingFile()或anExistingDirectory()*匹配器:
@Test
public void whenVerifyingFileOrDirExist_thenCorrect() {
File file = new File("src/test/resources/test1.in");
File dir = new File("src/test/resources");
assertThat(file, anExistingFile());
assertThat(dir, anExistingDirectory());
assertThat(file, anExistingFileOrDirectory());
assertThat(dir, anExistingFileOrDirectory());
}
结合两者的*anExistingFileOrDirectory()*匹配器也是可用的。