Java 单元测试实战——编写可测试代码的技巧

以下问题本文并未讨论:

  • 为什么需要单元测试
  • 单元测试框架/类库如何使用

依赖外置

方法内部不应该有外部依赖,如静态加载的配置、时间、ThreaLocal 等,这样会导致测试结果不稳定。

解决方法:

  1. 外部依赖作为方法参数
  2. 外部依赖作为对象依赖
 

java

代码解读

复制代码

@Slf4j @Value public class BadStaticVarDemo { Repo repo; // 待测试的代码 void trackUserAct(Object userAct) { switch (EnvUtils.region) { case "Jakarta" -> repo.save(userAct); default -> log.info("Forbid track user info"); } } } interface Repo { int save(Object userAct); } class EnvUtils { // 静态外部依赖 public static final String region = loadRegion("region"); private static String loadRegion(String key) { // 模拟从环境变量中拉取数据 return "Java"; } }

以上代码有两种修改方式,一是添加环境变量到方法参数,而是引用环境变量依赖,使用实体类包装静态方法为实例方法。

第一种方法适用于针对单个方法优化;第二种方法适用于多个方法优化。

总之,可测试性良好的代码不应该出现需要 mock 静态方法或者静态值的情形。

数据库操作外置

基本模式如下:

 

java

代码解读

复制代码

var data = fetchData(); var result = process(data); saveToRepo(result);

通过将数据库操作外置,使得 process 方法可以方便测试、复用和重构。

一般来说,数据库的读写操作无需写单元测试。

关于核心业务逻辑的分层处理推荐看看这本书: Domain Modeling Made Functional: Tackle Software Complexity with Domain-Driven Design and F#

ServiceImpl 应该如何测试

很多项目创建了 service 包,Service 可以作为无状态的业务逻辑访问接口,但是很多时候其实现几乎包括了所有的代码逻辑,正确的做法是仅将 service 视为不同领域任务的组合,封装具体逻辑到各个业务领域。

同一层次逻辑的代码应该放在一起,不同层次的代码需要区分。对于老旧系统,至少可以使用 提取方法 技巧优化代码层次。

Service 单测不应该涉及具体的逻辑,核心逻辑应该在另外的单元测试中单独测试。单测测试测试的内容应该是确保某些代码执行,如 Mockito.verify

暴露测试性

面向对象设计中要求最大封装性,减少对外暴露不必要的方法或字段。很多时候方法使用了 private 标识,但是我们有时候需要对 private 方法进行测试。

解决方法:使用包访问权限,方便测试。使用 @VisibleForTesting(Guava) 等注解标注方法。

TDD

个人理解:测试驱动开发需要程序员有非常好的代码直觉,需要良好的代码接口定义能力,很难实践。

使用实践建议

建议使用 JUnit 5 + Mockito + AssertJ (提供 fluent 语法)组合,大部分测试代码可以由 chatGPT 生成,仅需要补充测试 case或者略作修改。

简单示例

以下代码支持对不活跃用户生成相应的通知信息。

 

java

代码解读

复制代码

@Value class InactiveUserMessageGenerator { private static final ImmutableRangeMap<Duration, String> rangeSymbols = ImmutableRangeMap.<Duration, String>builder() .put(Range.closedOpen(Duration.ofDays(7L), Duration.ofDays(30L)), "一周") .put(Range.closedOpen(Duration.ofDays(30L), Duration.ofDays(365L)), "一个月") .put(Range.downTo(Duration.ofDays(365L), BoundType.CLOSED), "一年") .build(); private static final String template = "您已超过%s未登录"; /** * userId -> lastVisit */ Map<Long, Long> lastVisits; LocalDateTime now; public ImmutableMap<Long, Optional<String>> generateMessages() { return ImmutableMap.copyOf(Maps.transformValues(lastVisits, this::generateMessage)); } @VisibleForTesting Optional<String> generateMessage(long timeMillis) { LocalDateTime dt = formalizeDateTime(timeMillis); String s = rangeSymbols.get(Duration.between(dt, now)); return Optional.ofNullable(s).map(template::formatted); } @VisibleForTesting static LocalDateTime formalizeDateTime(long timeMillis) { return LocalDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), ZoneId.systemDefault()); } }

 

java

代码解读

复制代码

// 测试代码大部分可由 chatGPT 生成 class InactiveUserMessageGeneratorTest { private InactiveUserMessageGenerator messageGenerator; private LocalDateTime now; @BeforeEach void setUp() { now = LocalDateTime.now(); } @Test void testGenerateMessages() { // 准备测试数据 Map<Long, Long> lastVisits = new HashMap<>(); lastVisits.put(1L, now.minusDays(10) .atZone(ZoneId.systemDefault()) .toInstant() .toEpochMilli()); lastVisits.put(2L, now.minusDays(40) .atZone(ZoneId.systemDefault()) .toInstant() .toEpochMilli()); lastVisits.put(3L, now.minusDays(400) .atZone(ZoneId.systemDefault()) .toInstant() .toEpochMilli()); // 初始化测试对象 messageGenerator = new InactiveUserMessageGenerator(lastVisits, now); // 调用被测试方法 Map<Long, Optional<String>> messages = messageGenerator.generateMessages(); // 使用 AssertJ 进行断言 assertThat(messages.get(1L)).isPresent() .contains("您已超过一周未登录"); assertThat(messages.get(2L)).isPresent() .contains("您已超过一个月未登录"); assertThat(messages.get(3L)).isPresent() .contains("您已超过一年未登录"); } @Test void testGenerateMessage() { Map<Long, Long> lastVisits = new HashMap<>(); lastVisits.put(1L, now.minusDays(10) .atZone(ZoneId.systemDefault()) .toInstant() .toEpochMilli()); lastVisits.put(2L, now.minusDays(40) .atZone(ZoneId.systemDefault()) .toInstant() .toEpochMilli()); lastVisits.put(3L, now.minusDays(400) .atZone(ZoneId.systemDefault()) .toInstant() .toEpochMilli()); messageGenerator = new InactiveUserMessageGenerator(lastVisits, now); // 测试不同时间范围内的消息生成 long timeMillis = now.minusDays(10) .atZone(ZoneId.systemDefault()) .toInstant() .toEpochMilli(); Optional<String> message = messageGenerator.generateMessage(timeMillis); assertThat(message).isPresent() .contains("您已超过一周未登录"); timeMillis = now.minusDays(40) .atZone(ZoneId.systemDefault()) .toInstant() .toEpochMilli(); message = messageGenerator.generateMessage(timeMillis); assertThat(message).isPresent() .contains("您已超过一个月未登录"); timeMillis = now.minusDays(400) .atZone(ZoneId.systemDefault()) .toInstant() .toEpochMilli(); message = messageGenerator.generateMessage(timeMillis); assertThat(message).isPresent() .contains("您已超过一年未登录"); } @Test void testFormalizeDateTime() { // 测试 2024 年 1 月 1 日上午 10 点的时间戳 ZonedDateTime zdt = ZonedDateTime.of(LocalDateTime.of(2024, 1, 1, 10, 0), ZoneId.systemDefault()); long timeMillis = zdt.toInstant() .toEpochMilli(); LocalDateTime dateTime = InactiveUserMessageGenerator.formalizeDateTime(timeMillis); assertThat(dateTime).isEqualTo("2024-01-01T10:00:00"); zdt = ZonedDateTime.of(LocalDateTime.of(2023, 12, 25, 15, 30), ZoneId.systemDefault()); timeMillis = zdt.toInstant().toEpochMilli(); dateTime = InactiveUserMessageGenerator.formalizeDateTime(timeMillis); assertThat(dateTime).isEqualTo("2023-12-25T15:30:00"); zdt = ZonedDateTime.of(LocalDateTime.of(2022, 6, 15, 8, 45), ZoneId.systemDefault()); timeMillis = zdt.toInstant().toEpochMilli(); dateTime = InactiveUserMessageGenerator.formalizeDateTime(timeMillis); assertThat(dateTime).isEqualTo("2022-06-15T08:45:00"); } }

总结

在代码编写时就应该考虑可测试性,这样方便之后的测试和问题排查。

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值