
1. JUnit单元测试基础与BMI计算器实战第一次接触JUnit时我盯着那些Test注解发懵——直到把BMI计算器的算法拆解成测试用例才恍然大悟。单元测试就像给代码做体检而JUnit就是最趁手的检查仪器。先看这个简单的BMI分类逻辑public String getBMIType() { if(bmi18.5) return 偏瘦; else if(bmi24) return 正常; else if(bmi28) return 偏胖; else return 肥胖; }1.1 测试环境搭建的坑与经验在Eclipse里新建JUnit测试类时我遇到过两个典型问题忘记添加JUnit库依赖导致Test注解报红测试类和方法没有用public修饰运行按钮是灰色的正确姿势是用Maven管理依赖dependency groupIdorg.junit.jupiter/groupId artifactIdjunit-jupiter/artifactId version5.8.2/version scopetest/scope /dependency1.2 第一个有效测试用例给偏瘦分类写测试时我最初直接写死了身高体重Test void testThin() { BMI bmi new BMI(45, 1.6); assertEquals(偏瘦, bmi.getBMIType()); }后来发现更好的做法是用边界值Test void testThinBoundary() { // 18.5的边界值1.6m身高对应47.36kg BMI bmi new BMI(47.35, 1.6); assertEquals(偏瘦, bmi.getBMIType()); }2. 企业级测试策略设计在电商项目踩过坑后我总结出测试用例设计的三明治法则2.1 黑盒测试方法实战等价类划分示例BMI场景分类输入范围有效等价类无效等价类偏瘦18.517.5-1正常18.5~24200偏胖24~2826身高为负数边界值分析的经典场景ParameterizedTest ValueSource(doubles {17.9, 18.4, 18.5, 23.9, 24.0, 27.9, 28.0}) void testBoundaries(double bmiValue) { BMI bmi new BMI(); bmi.setBMI(bmiValue); assertNotNull(bmi.getBMIType()); }2.2 测试生命周期管理在物流系统中我用BeforeEach初始化运单号生成器class WaybillTest { private WaybillGenerator generator; BeforeEach void init() { generator new WaybillGenerator(); generator.setPrefix(SF); } Test void generateId() { String id generator.generate(); assertTrue(id.startsWith(SF2023)); } }3. 高级测试技巧与异常处理支付模块的测试让我深刻认识到异常处理的重要性...3.1 参数化测试进阶用CSV文件管理测试数据ParameterizedTest CsvFileSource(resources /bmi_testcases.csv) void testWithCsv(double weight, double height, String expected) { BMI bmi new BMI(weight, height); assertEquals(expected, bmi.getBMIType()); }bmi_testcases.csv示例45,1.6,偏瘦 55,1.6,正常 68,1.6,偏胖 80,1.6,肥胖 0,1.6,无效输入3.2 超时与并发测试测试缓存服务时这样验证性能Test Timeout(5) void cacheResponseUnderLoad() throws Exception { ExecutorService pool Executors.newFixedThreadPool(10); for(int i0; i100; i) { pool.submit(() - { assertNotNull(cache.get(key)); }); } pool.shutdown(); assertTrue(pool.awaitTermination(10, SECONDS)); }4. 企业级集成实践在CI流水线中我们这样配置Maven插件plugin groupIdorg.apache.maven.plugins/groupId artifactIdmaven-surefire-plugin/artifactId version3.0.0/version configuration includes include**/*Test.java/include /includes excludes exclude**/StressTest.java/exclude /excludes /configuration /plugin4.1 测试报告优化使用Allure生成可视化报告dependency groupIdio.qameta.allure/groupId artifactIdallure-junit5/artifactId version2.13.0/version /dependency关键注解示例Epic(健康管理) Feature(BMI计算) Story(用户BMI分类) Test void shouldReturnObeseWhenBMIOver28() { // ... }4.2 测试覆盖率控制JaCoCo配置阈值示例plugin groupIdorg.jacoco/groupId artifactIdjacoco-maven-plugin/artifactId version0.8.7/version executions execution goals goalprepare-agent/goal /goals /execution execution idcheck-coverage/id goals goalcheck/goal /goals configuration rules rule limit counterLINE/counter valueCOVEREDRATIO/value minimum0.8/minimum /limit /rule /rules /configuration /execution /executions /plugin