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);
相关推荐
Warren989 小时前
Pytest Fixture 作用域详解:Function、Class、Module、Session 怎么选
面试·职场和发展·单元测试·pytest·pip·模块测试·jira
一晌小贪欢2 天前
Python 测试利器:使用 pytest 高效编写和管理单元测试
python·单元测试·pytest·python3·python测试
汽车仪器仪表相关领域2 天前
MTX-A 模拟废气温度(EGT)计 核心特性与车载实操指南
网络·人工智能·功能测试·单元测试·汽车·可用性测试
我命由我123452 天前
Android 控件 - 最简单的 Notification、Application Context 应用于 Notification
android·java·开发语言·junit·android studio·android jetpack·android-studio
卓码软件测评2 天前
第三方软件课题验收测试【使用Docker容器部署LoadRunner负载生成器以实现弹性压测 】
测试工具·docker·容器·性能优化·单元测试·测试用例
android_cai_niao2 天前
JUnit 4.x最新版本
junit·junit5·junit4
Apifox.3 天前
Apifox 1 月更新|MCP 调试、测试套件、测试报告重构、网络信息查看、Hoppscotch 导入
前端·人工智能·测试工具·单元测试·团队开发
快乐肚皮3 天前
OpenResty:Nginx的进化之路
nginx·junit·openresty
卓码软件测评3 天前
第三方移动应用测试机构:【移动应用性能测试:使用LoadRunner的Mobile Application - HTTP/HTML协议】
测试工具·ci/cd·性能优化·单元测试·测试用例
汽车仪器仪表相关领域3 天前
70A大电流+三档电压可调:Midtronics MSP-070系列电源充电器汽车ECU刷新与电池维护实战全解
人工智能·功能测试·单元测试·汽车·可用性测试