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);
相关推荐
emo了小猫1 天前
Redis 执行 Lua 脚本过程中报错,会发生什么
redis·junit·lua
2401_861277551 天前
适合使用判定表设计测试用例的条件,如何使用判定表构造测试用例,举例说明
功能测试·单元测试·测试用例
SoleMotive.4 天前
redis实现漏桶算法--https://blog.csdn.net/m0_74908430/article/details/155076710
redis·算法·junit
꧁༺℘₨风、凌๓༻꧂5 天前
C# MES .NET Framework Winform 单元测试
单元测试·c#·.net
虹科网络安全5 天前
艾体宝干货 | Redis Python 开发系列#4 保证原子性与性能
redis·python·junit
我发在否5 天前
OpenResty > 平滑升级:1.25.x → 1.27.x
junit·openresty
IMPYLH5 天前
Lua 的 pairs 函数
开发语言·笔记·后端·junit·单元测试·lua
倚肆5 天前
Spring Boot 测试注解全解:从单元测试到集成测试
spring boot·单元测试·集成测试
安冬的码畜日常5 天前
【JUnit实战3_35】第二十二章:用 JUnit 5 实现测试金字塔策略
测试工具·junit·单元测试·集成测试·系统测试·bdd·测试金字塔