1. 概述

本文将深入探讨 Hamcrest 的文件匹配器(File Matchers)。在之前的 Hamcrest 测试指南 中我们已经介绍了 Hamcrest 匹配器的基础知识。接下来,我们将聚焦于文件匹配器的专项使用。

2. Maven 配置

首先需要在 pom.xml 中添加以下依赖:

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>java-hamcrest</artifactId>
    <version>2.0.0.0</version>
    <scope>test</scope>
</dependency>

最新版 java-hamcrest 可从 Maven Central 下载。下面开始探索 Hamcrest 文件匹配器的核心功能。

3. 文件属性验证

Hamcrest 提供了多种匹配器来验证常用文件属性,使用起来简单粗暴:

3.1 文件名验证

通过 aFileNamed() 结合字符串匹配器验证文件名:

@Test
public void whenVerifyingFileName_thenCorrect() {
    File file = new File("src/test/resources/test1.in");
 
    assertThat(file, aFileNamed(equalToIgnoringCase("test1.in")));
}

3.2 文件路径验证

同样结合字符串匹配器验证路径(支持规范路径和绝对路径):

@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")));
}

3.3 文件大小验证

直接验证文件字节数:

@Test
public void whenVerifyingFileSize_thenCorrect() {
    File file = new File("src/test/resources/test1.in");

    assertThat(file, aFileWithSize(11));
    assertThat(file, aFileWithSize(greaterThan(1L)));;
}

3.4 读写权限验证

检查文件是否可读/可写:

@Test
public void whenVerifyingFileIsReadableAndWritable_thenCorrect() {
    File file = new File("src/test/resources/test1.in");

    assertThat(file, aReadableFile());
    assertThat(file, aWritableFile());        
}

4. 文件存在性验证

验证文件或目录是否存在时,使用以下匹配器:

@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());
}

✅ 关键点:

  • anExistingFile():专门验证文件存在
  • anExistingDirectory():专门验证目录存在
  • anExistingFileOrDirectory():通用验证(文件或目录均可)

⚠️ 注意:当路径不存在时,这些匹配器会直接抛出断言错误,无需额外处理异常。

5. 总结

本文系统梳理了 Hamcrest 文件匹配器的核心用法,包括:

  • 文件属性验证(名称/路径/大小/权限)
  • 文件存在性验证
  • 实际测试场景的最佳实践

完整示例代码已托管在 GitHub。建议直接克隆项目运行测试,比看文档更直观。


原始标题:Hamcrest File Matchers