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:


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:

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:

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:

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:

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:

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.

Generic bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Comments are closed on this article!