JUnit单元测试

结果断言

java 复制代码
Assertions.assertEquals(Object expected, Object actual)
Assertions.assertDoesNotThrow(Executable executable)
Assertions.assertThrows(Class<T> expectedType, Executable executable)
Assertions.assertTrue(boolean condition)
Assertions.assertNotNull(Object actual)

Mock

java 复制代码
// 创建 Mock 对象
List<String> mockedList = mock(List.class);
        
// 设置 Mock 行为
when(mockedList.get(0)).thenReturn("first");
when(mockedList.size()).thenReturn(10);

// 使用参数匹配器
when(mockList.get(anyInt())).thenReturn("element");

// 静态方法
try (MockedStatic<UtilityClass> mockedStatic = mockStatic(UtilityClass.class)) {
        // Mock 静态方法
        mockedStatic.when(() -> UtilityClass.staticMethod("test"))
                   .thenReturn("mocked result");
        
        assertEquals("mocked result", UtilityClass.staticMethod("test"));
}

// 设置 Mock 行为:当调用 setString 方法时,什么都不做
Mockito.doNothing().when(ppstmt).setString(anyInt(), anyString());

// 构造方法
MockedConstruction<MyClass> myClassMockedConstruction = Mockito.mockConstruction(MyClass.class,
                     (mock, context) -> Mockito.when(mock.someMethod(anyString(), anyString(), anyString(), any())).thenReturn("xxx)))

读取测试文件

java 复制代码
public static String readFile(String filePath) {
        File jsonFile = UsFileUtils.getFile(filePath);
        StringBuilder stringBuilder = new StringBuilder();
        try {
            FileReader fileReader = UsFileUtils.getFileReader(jsonFile);
            char[] buffer = new char[1024];
            int length;
            while ((length = fileReader.read(buffer)) != -1) {
                stringBuilder.append(buffer, 0, length);
            }
            fileReader.close();
        } catch (Exception e) {
            log.error("read datasource.json fail, {}", ExceptionUtil.getExceptionInfo(e));
        }
        return stringBuilder.toString();
}

SpringBoot配置属性绑定测试

java 复制代码
@Test
void testGetInnerDataSourceMap() {
        Map<String, String> properties = new HashMap<String, String>() {{
            put("xxx.yyy.zzz1", "1");
            put("xxx.yyy.zzz2", "2");
            put("xxx.yyy.zzz3", "3");
        }};
        ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
        Binder binder = new Binder(source);
        BindResult<beanName> bindResult = binder.bind("xxx", beanName.class);
        DataSourceConfig boundProperties = bindResult.get();

        Assertions.assertEquals("1", boundProperties.getyyy().get("zzz1"));
        Assertions.assertEquals("2", boundProperties.getyyy().get("zzz2"));
        Assertions.assertEquals("3", boundProperties.getyyy().get("zzz3"));
}

@Configuration
@ConfigurationProperties(prefix = "xxx")
@Data
public class DataSourceConfig {
    private Map<String, String> yyy;
}

@TempDir临时目录注解,用于自动创建和清理临时目录

java 复制代码
@Test
void testClearFiles(@TempDir Path tempDir) {
        try {
            for (int i = 1; i <= 4; i++) {
                Path path = tempDir.resolve("tmpfile" + i);
                Files.createFile(path);
            }
        } catch (IOException e) {
            log.error("create files failed: {}", ExceptionUtil.getExceptionInfo(e));
        }
        FileAgeUtil.clearFiles(tempDir, 7L, ChronoUnit.DAYS, 3L);
        long count = 0;
        try (Stream<Path> paths = Files.walk(tempDir)) {
            count = paths.filter(Files::isRegularFile).count();
        } catch (IOException e) {
            log.error("count files failed: {}", ExceptionUtil.getExceptionInfo(e));
        }
        Assertions.assertEquals(3, count);
    }

通过Unsafe方法初始化对象

java 复制代码
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
Unsafe unsafe = (Unsafe) field.get(null);
MyClass myClass= (MyClass) unsafe.allocateInstance(MyClass.class);
相关推荐
叶落无痕529 小时前
Electron应用自动化测试实例
前端·javascript·功能测试·测试工具·electron·单元测试
汽车仪器仪表相关领域9 小时前
工况模拟精准检测,合规减排赋能行业 ——NHASM-1 型稳态工况法汽车排气检测系统项目实战经验分享
数据库·算法·单元测试·汽车·压力测试·可用性测试
码农水水12 小时前
大疆Java面试被问:TCC事务的悬挂、空回滚问题解决方案
java·开发语言·人工智能·面试·职场和发展·单元测试·php
卓码软件测评17 小时前
CMA-CNAS软件测评报告机构【Apifox动态Mock响应处理复杂业务逻辑设计】
测试工具·性能优化·单元测试·测试用例
_200_17 小时前
Lua 流程控制
开发语言·junit·lua
孙琦Ray17 小时前
GitHub开源项目日报 · 2026年1月7日 · 本期热门开源全景
单元测试·开源·前端调试·浏览器自动化·知识管理·ai代理·跨语言序列化
程序员三藏18 小时前
单元测试详解
自动化测试·软件测试·python·测试工具·职场和发展·单元测试·测试用例
卓码软件测评2 天前
CMA/CNAS双资质软件测评机构【Apifox高效编写自动化测试用例的技巧和规范】
测试工具·ci/cd·性能优化·单元测试·测试用例
回眸&啤酒鸭2 天前
【回眸】Tessy 单元测试软件使用指南(五)进阶报错之解决指南(含泪整理)
单元测试
小二·2 天前
前端测试体系完全指南:从 Vitest 单元测试到 Cypress E2E(Vue 3 + TypeScript)
前端·typescript·单元测试