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

如何使用JUnit和Mockito测试Java中带文件创建覆盖逻辑的方法?

JUnit + Mockito 测试文件创建方法示例

所需依赖

确保项目中引入JUnit 5和Mockito的依赖(以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>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>4.11.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-junit-jupiter</artifactId>
    <version>4.11.0</version>
    <scope>test</scope>
</dependency>

测试类实现

假设待测试类名为FileGenerator,测试类代码如下:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
public class FileGeneratorTest {

    @Mock
    private Logger logger;

    @InjectMocks
    private FileGenerator fileGenerator;

    private static final String TEST_FECHA = "20240520";
    private static final String EXPECTED_FILE_NAME = ConstantsFiles.FILE_NAME_PE + TEST_FECHA + ConstantsFiles.FILE_EXTENSION;
    private static final String EXPECTED_FILE_PATH = ConstantsFiles.FILE_PATH_PE + EXPECTED_FILE_NAME;

    @Test
    void getFilePE_WhenFileDoesNotExist_CreatesFileSuccessfully() throws IOException {
        // Mock File实例及createNewFile行为
        try (MockedStatic<File> mockedFile = mockStatic(File.class)) {
            File mockFile = mock(File.class);
            mockedFile.when(() -> new File(EXPECTED_FILE_PATH)).thenReturn(mockFile);
            when(mockFile.createNewFile()).thenReturn(true);
            when(mockFile.getName()).thenReturn(EXPECTED_FILE_NAME);

            String resultPath = fileGenerator.getFilePE(TEST_FECHA);

            // 验证返回路径正确
            assertEquals(EXPECTED_FILE_PATH, resultPath);
            // 验证日志输出
            verify(logger).info("Generando archivo para PE");
            verify(logger).info(EXPECTED_FILE_PATH);
            verify(logger).info("Archivo creado con exito " + EXPECTED_FILE_NAME);
            // 验证删除方法未被调用
            try (MockedStatic<Files> mockedFiles = mockStatic(Files.class)) {
                mockedFiles.verify(() -> Files.deleteIfExists(Paths.get(EXPECTED_FILE_PATH)), never());
            }
        }
    }

    @Test
    void getFilePE_WhenFileExists_DeletesExistingFile() throws IOException {
        // Mock File.createNewFile返回false(文件已存在)
        try (MockedStatic<File> mockedFile = mockStatic(File.class)) {
            File mockFile = mock(File.class);
            mockedFile.when(() -> new File(EXPECTED_FILE_PATH)).thenReturn(mockFile);
            when(mockFile.createNewFile()).thenReturn(false);

            // Mock Files.deleteIfExists行为
            try (MockedStatic<Files> mockedFiles = mockStatic(Files.class)) {
                mockedFiles.when(() -> Files.deleteIfExists(Paths.get(EXPECTED_FILE_PATH))).thenReturn(true);

                String resultPath = fileGenerator.getFilePE(TEST_FECHA);

                assertEquals(EXPECTED_FILE_PATH, resultPath);
                verify(logger).info("Generando archivo para PE");
                verify(logger).info(EXPECTED_FILE_PATH);
                // 验证删除方法被调用一次
                mockedFiles.verify(() -> Files.deleteIfExists(Paths.get(EXPECTED_FILE_PATH)), times(1));
            }
        }
    }

    @Test
    void getFilePE_WhenIOExceptionThrown_LogsErrorAndReturnsPath() throws IOException {
        IOException testException = new IOException("Test IO Error");
        // Mock File.createNewFile抛出异常
        try (MockedStatic<File> mockedFile = mockStatic(File.class)) {
            File mockFile = mock(File.class);
            mockedFile.when(() -> new File(EXPECTED_FILE_PATH)).thenReturn(mockFile);
            when(mockFile.createNewFile()).thenThrow(testException);

            String resultPath = fileGenerator.getFilePE(TEST_FECHA);

            assertEquals(EXPECTED_FILE_PATH, resultPath);
            // 验证错误日志被记录
            verify(logger).error("Error, el archivo no se pudo generar: " + testException.getMessage(), testException);
        }
    }
}

测试说明

  • 文件不存在场景:验证文件创建成功,对应日志正确输出,且删除方法未被调用。
  • 文件已存在场景:验证文件删除方法被调用,返回路径符合预期。
  • 异常场景:验证IO异常被捕获并记录错误日志,仍返回计算后的文件路径。

内容的提问来源于stack exchange,提问作者Jonathan Ortiz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:25:47