hamcrest-file-matchers
Hamcrest File Matchers
1. Overview
We discussed Hamcrest Matchers in general before in the previous Testing with Hamcrest article. In the next sections, we’ll focus only File Matchers.
2. Maven Configuration
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>2.0.0.0</version>
<scope>test</scope>
</dependency>
The latest version of java-hamcrest can be downloaded from Maven Central.
Let’s continue with exploring the Hamcrest File Matchers.
3. File Properties
Let’s see how we can verify the File name using aFileNamed() combined with a String Matcher:
@Test
public void whenVerifyingFileName_thenCorrect() {
File file = new File("src/test/resources/test1.in");
assertThat(file, aFileNamed(equalToIgnoringCase("test1.in")));
}
We can also assess the file path – again in combination with a String Matcher:
@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")));
}
Let’s also see a file’s size – in bytes:
@Test
public void whenVerifyingFileSize_thenCorrect() {
File file = new File("src/test/resources/test1.in");
assertThat(file, aFileWithSize(11));
assertThat(file, aFileWithSize(greaterThan(1L)));;
}
Finally, we can check if a File is readable and writable:
@Test
public void whenVerifyingFileIsReadableAndWritable_thenCorrect() {
File file = new File("src/test/resources/test1.in");
assertThat(file, aReadableFile());
assertThat(file, aWritableFile());
}
4. Existing File Matcher
If we want to verify that a File or directory exists, we can use the anExistingFile() or anExistingDirectory() matchers:
@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());
}
The anExistingFileOrDirectory() matcher that combines the two is also available.
5. Conclusion
As always, the full source code for the examples is available over on GitHub.