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

如何使用JUnit与Mockito测试Java中的日期处理方法?新手求示例

日期格式转换方法的JUnit+Mockito测试方案

针对你提供的fileAEDateFormat静态方法,我们可以从正常格式转换和解析异常处理两个核心场景入手测试,以下是具体思路和代码示例:

核心测试场景

  • 合法日期输入:传入符合ConstantsFiles.DATE_FORMAT_CM格式的字符串,验证转换后的结果是否匹配ConstantsFiles.DATE_FORMAT格式。
  • 非法日期输入:传入不符合格式的字符串,验证方法返回null,且错误日志被正确记录。

测试代码示例(JUnit 5 + Mockito)

假设你的方法所在类为DateConverter,ConstantsFiles中的日期常量示例为:DATE_FORMAT_CM = "dd/MM/yyyy"、DATE_FORMAT = "yyyy-MM-dd"(可根据实际值调整)

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import java.text.ParseException;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

class DateConverterTest {

    // 多组合法输入测试,覆盖不同日期场景
    @ParameterizedTest
    @CsvSource({
            "01/01/2024, 2024-01-01",
            "31/12/2023, 2023-12-31",
            "15/06/2022, 2022-06-15"
    })
    void fileAEDateFormat_ValidInput_ReturnsFormattedDate(String inputDate, String expectedOutput) {
        String result = DateConverter.fileAEDateFormat(inputDate);
        assertEquals(expectedOutput, result);
    }

    // 非法输入测试,验证异常处理逻辑
    @Test
    void fileAEDateFormat_InvalidInput_ReturnsNullAndLogsError() {
        String invalidDate = "2024/13/01"; // 无效月份,触发ParseException

        // Mock静态日志(假设使用SLF4J的Logger)
        try (MockedStatic<org.slf4j.LoggerFactory> mockedLoggerFactory = Mockito.mockStatic(org.slf4j.LoggerFactory.class)) {
            org.slf4j.Logger mockLogger = mock(org.slf4j.Logger.class);
            mockedLoggerFactory.when(() -> org.slf4j.LoggerFactory.getLogger(DateConverter.class)).thenReturn(mockLogger);

            String result = DateConverter.fileAEDateFormat(invalidDate);

            // 验证返回值为null
            assertNull(result);
            // 验证错误日志被正确调用
            verify(mockLogger).error(contains(ConstantsFiles.PARSE_EXCEPCION), any(ParseException.class));
        }
    }
}

关键说明

  • 参数化测试:用@ParameterizedTest配合@CsvSource可以一次性测试多组输入,避免重复代码,覆盖更多边界日期(比如月末、年初)。
  • 静态日志Mock:由于方法中使用了静态Logger,需要用Mockito的MockedStatic来模拟LoggerFactory的静态方法,确保错误日志的输出逻辑符合预期。如果你的项目使用其他日志框架(如java.util.logging),只需调整对应的Mock逻辑即可。
  • 异常验证:非法输入测试中,除了检查返回值,还要验证异常被捕获并记录日志,确保方法的容错逻辑正常运行。

内容的提问来源于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 11:27:31