首页 > 解决方案 > 复杂对象的 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));
}

有没有办法创建一个更紧凑的测试,避免所有这些实例化MovementItemMovementItem是否可以使用 Mockito模拟这些实例的创建?

标签: javaunit-testingjunitjunit5

解决方案


推荐阅读