Contents

Assert验证对象是否属于特定类型

1. 概述

在本文中,我们将探讨如何验证对象是否属于特定类型。我们将研究不同的测试库以及它们提供的断言对象类型的方法。

我们可能需要执行此操作的场景可能会有所不同。一种常见的情况是,当我们利用接口作为方法的返回类型,但随后根据返回的具体对象,我们想要执行不同的操作。单元测试可以帮助我们确定 返回的对象是否具有我们期望的类。

2. 示例场景

让我们想象一下,我们正在根据树木是否在冬天落叶对它们进行分类。我们有两个类,Evergreen和 Deciduous,它们都实现了Tree接口*。*我们有一个简单的排序器,它根据树的名称返回正确的类型:

Tree sortTree(String name) {
    List<String> deciduous = List.of("Beech", "Birch", "Ash", "Whitebeam", "Hornbeam", "Hazel & Willow");
    List<String> evergreen = List.of("Cedar", "Holly", "Laurel", "Olive", "Pine");
    if (deciduous.contains(name)) {
        return new Deciduous(name);
    } else if (evergreen.contains(name)) {
        return new Evergreen(name);
    } else {
        throw new RuntimeException("Tree could not be classified");
    }
}

让我们探索如何测试实际返回的Tree类型。

2.1. 使用 JUnit5 进行测试

如果我们想使用JUnit5 ,我们可以使用assertEquals方法检查对象的类是否等于我们正在测试的类

@Test
public void sortTreeShouldReturnEvergreen_WhenPineIsPassed() {
    Tree tree = tested.sortTree("Pine");
    assertEquals(tree.getClass(), Evergreen.class);
}

2.2. 使用 Hamcrest 进行测试

使用Hamcrest 库时,我们可以使用 assertThat 和 instanceOf方法

@Test
public void sortTreeShouldReturnEvergreen_WhenPineIsPassed() {
Tree tree = tested.sortTree("Pine");
assertThat(tree, instanceOf(Evergreen.class));
}

当我们使用org.hamcrest.Matchers.isA导入时,我们可以使用一个快捷版本:

assertThat(tree, isA(Evergreen.class));

2.3. 使用 AssertJ 进行测试

我们还可以使用AssertJ Core 库的isExactlyInstanceOf方法

@Test
public void sortTreeShouldReturnEvergreen_WhenPineIsPassed() {
    Tree tree = tested.sortTree("Pine");
    assertThat(tree).isExactlyInstanceOf(Evergreen.class);
}

完成相同测试的另一种方法是使用hasSameClassAs方法

@Test
public void sortTreeShouldReturnDecidious_WhenBirchIsPassed() {
    Tree tree = tested.sortTree("Birch");
    assertThat(tree).hasSameClassAs(new Deciduous("Birch"));
}