1. Overview
In this tutorial, we’ll discuss Hamcrest File Matchers.
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
First, we need to add the following dependency to our pom.xml:
<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
Hamcrest provides several matchers that verify commonly used 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
In this quick article, we went through Hamcrest File Matchers and their use.
As always, the full source code for the examples is available over on GitHub.