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);
相关推荐
软件检测小牛玛12 小时前
软件功能测试找谁做?第三方软件检测机构推荐:中承信安
功能测试·单元测试·软件测试报告·软件功能测试·第三方软件测评
软件检测小牛玛2 天前
具备软件功能测试资质的机构哪家更权威?山东软件测评机构 中承信安
功能测试·单元测试·软件测试报告·软件测评机构
闻哥2 天前
从测试坏味道到优雅实践:打造高质量单元测试
java·面试·单元测试·log4j·springboot
Warren983 天前
Pytest Fixture 作用域与接口测试 Token 污染问题实战解析
功能测试·面试·单元测试·集成测试·pytest·postman·模块测试
知行合一。。。3 天前
程序中的log4j、stderr、stdout日志
python·单元测试·log4j
测试秃头怪3 天前
面试大厂就靠这份软件测试八股文了【含答案】
自动化测试·软件测试·python·功能测试·面试·职场和发展·单元测试
测试大圣3 天前
软件测试基础知识总结(超全的)
软件测试·python·功能测试·测试工具·职场和发展·单元测试·测试用例
CodeCraft Studio4 天前
【Parasoft案例分享】在 DO-178C 标准下,如何实现航空嵌入式软件测试自动化
单元测试·自动化·静态分析·代码覆盖率·parasoft·do-178c·软件自动化测试
懒羊羊大王&4 天前
软件测试之博客系统项目实战(补充和解析部分)
selenium·单元测试·测试用例·集成测试