java - 复杂对象的 JUnit 测试 - 在测试中创建大量实例
问题描述
我必须totalNumber
使用 JUnit(如果需要 Mockito)测试以下类的方法:
@RequiredArgsConstructor
public final class TotalSum {
private final String reason;
private final List<ScopeItem> scopes;
public int totalNumber() {
return scopes.stream()
.collect(Collectors.toList())
.stream()
.flatMap(c -> c.getMovements().stream())
.collect(Collectors.toList()).stream()
.filter(aMovement -> reason.equals(aMovement.getReason()))
.mapToInt(MovementItem::getNumber)
.sum();
}
}
该totalNumber
方法将所有具有一定值作为原因的运动的次数相加。
这些是涉及的类:
@RequiredArgsConstructor
@Getter
public class ScopeItem {
private List<MovementItem> movements;
}
----------------------------------------
@Getter
@RequiredArgsConstructor
public class MovementItem {
private String reason;
private int number;
}
出于测试目的,我添加了以下测试:
@Test
void totalMov() {
MovementItem aMov = new MovementItem("string1", 9);
MovementItem aMov_1 = new MovementItem("string1", 3);
MovementItem aMov_2 = new MovementItem("string2", 7);
MovementItem aMov_3 = new MovementItem("string1", 5);
MovementItem aMov_4 = new MovementItem("string2", 4);
MovementItem aMov_5 = new MovementItem("string3", 1);
MovementItem aMov_6 = new MovementItem("string1", 4);
MovementItem aMov_7 = new MovementItem("string2", 5);
MovementItem aMov_8 = new MovementItem("string3", 2);
List<MovementItem> l1 = new ArrayList<>(Arrays.asList(aMov, aMov_1, aMov_2));
List<MovementItem> l2 = new ArrayList<>(Arrays.asList(aMov_3, aMov_4, aMov_5));
List<MovementItem> l3 = new ArrayList<>(Arrays.asList(aMov_6, aMov_7, aMov_8));
ScopeItem aScope = new ScopeItem(l1);
ScopeItem aScope1 = new ScopeItem(l2);
ScopeItem aScope2 = new ScopeItem(l3);
List<ScopeItem> scopes = new ArrayList<>(Arrays.asList(aScope, aScope1, aScope2));
assertEquals(21, new TotalSum("string1", scopes));
assertEquals(16, new TotalSum("string2", scopes));
assertEquals(3, new TotalSum("string3", scopes));
}
有没有办法创建一个更紧凑的测试,避免所有这些实例化MovementItem
?MovementItem
是否可以使用 Mockito模拟这些实例的创建?
解决方案
推荐阅读
- r - 错误:stat_smooth 需要以下缺失的美学:x, y enen 当定义 x 和 y
- nestjs - 插入实体订阅者后 typeorm 更新实体
- python - Python3 - 将每个字符附加到字符串(制作一行)
- python - SQLAlchemy For a Read-only Query, what to use: session.expire() vs session.commit()?
- angular - 为什么变更检测被调用两次?
- asp.net-mvc - 如果停止 iss 默认网站仍会在 SignalR 客户端中获得响应
- c# - C# enum.ToString() 装箱:解决还是压制?
- angular - 如何在 React 中使用支持角度的库?
- javascript - Vue 变量不渲染条件元素 v-if
- ubuntu - Jenkins 关机后无法启动