You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用简单JUnit测试校验方法File入参正确性及文件名是否合规

实现方案

第一步:明确校验规则 + 补充原类入参校验

首先先确定通用的入参和文件名校验规则,你也可以根据自己的业务需求调整:

  • 入参File不能为null
  • File必须为真实存在的文件,不能是目录
  • 文件名必须以.xml为后缀

原XML2JSON类的parse方法目前没有入参校验,我们先补充校验逻辑,避免非法参数触发未知报错:

public class XML2JSON {
    public static int PRETTY_PRINT_INDENT_FACTOR = 4;

    public DBObject parse(File file) throws IOException {
        // 新增入参校验逻辑
        if (file == null) {
            throw new IllegalArgumentException("入参File不能为null");
        }
        if (!file.exists() || file.isDirectory()) {
            throw new IllegalArgumentException("入参File必须是存在的普通文件");
        }
        if (!file.getName().toLowerCase().endsWith(".xml")) {
            throw new IllegalArgumentException("文件名必须以.xml为后缀");
        }

        BufferedReader br = new BufferedReader(new FileReader(file));
        int ptr = 0;
        StringBuilder builder = new StringBuilder();
        while ((ptr = br.read()) != -1) {
            builder.append((char) ptr);
        }
        String xml = builder.toString();

        XmlMapper xmlMapper = new XmlMapper();
        JsonNode node = xmlMapper.readTree(xml.getBytes());
        ObjectMapper jsonMapper = new ObjectMapper();
        String json = jsonMapper.writeValueAsString(node);
        out.println(json);
        return (DBObject) JSON.parse(String.valueOf(json));
    }
}

第二步:编写JUnit 5测试用例

我们用JUnit 5自带的@TempDir注解生成临时测试文件,无需手动清理测试垃圾,覆盖所有合法/非法场景:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.*;

class XML2JSONTest {

    private final XML2JSON xml2JSON = new XML2JSON();

    // 测试入参为null的场景
    @Test
    void parse_shouldThrowExceptionWhenFileIsNull() {
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, 
            () -> xml2JSON.parse(null));
        assertEquals("入参File不能为null", exception.getMessage());
    }

    // 测试入参为目录的场景
    @Test
    void parse_shouldThrowExceptionWhenFileIsDirectory(@TempDir Path tempDir) {
        File dir = tempDir.toFile();
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
            () -> xml2JSON.parse(dir));
        assertEquals("入参File必须是存在的普通文件", exception.getMessage());
    }

    // 测试文件存在但后缀不是xml的场景
    @Test
    void parse_shouldThrowExceptionWhenFileSuffixNotXml(@TempDir Path tempDir) throws IOException {
        // 创建后缀为txt的测试文件
        Path txtFile = tempDir.resolve("test.txt");
        Files.createFile(txtFile);
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
            () -> xml2JSON.parse(txtFile.toFile()));
        assertEquals("文件名必须以.xml为后缀", exception.getMessage());
    }

    // 测试合法xml文件的正常流程
    @Test
    void parse_shouldReturnDbObjectWhenFileIsValid(@TempDir Path tempDir) throws IOException {
        // 构造测试xml内容
        String testXml = "<root><name>测试</name><age>18</age></root>";
        Path xmlFile = tempDir.resolve("test.xml");
        Files.write(xmlFile, testXml.getBytes());

        DBObject result = xml2JSON.parse(xmlFile.toFile());
        // 校验返回结果不为空,且内容符合预期
        assertNotNull(result);
        assertEquals("测试", result.get("name"));
        assertEquals("18", result.get("age"));
    }
}

依赖说明

如果你的项目还没引入JUnit 5,需要在pom.xml(Maven项目)添加以下依赖:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.9.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.9.2</version>
    <scope>test</scope>
</dependency>

如果使用JUnit 4,把测试用例的注解对应换成JUnit 4的写法,临时文件可以用TemporaryFolder规则实现即可。

内容的提问来源于stack exchange,提问作者Dincher Selimov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 14:57:04