You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JUnit测试类方法咨询:电影导演排序Comparator测试与ArrayList添加异常

嘿,我来帮你梳理下这两个问题的解决思路,都是JUnit测试里常见的小坑,咱们一个个来搞定~

问题1:JUnit测试类中无法调用ArrayList的add方法添加Movie对象

先从几个常见的排查方向入手,大概率能找到问题:

  • 检查集合是否不可变:如果你是用Collections.unmodifiableList()或者Guava的ImmutableList创建的集合,那调用add()肯定会抛出UnsupportedOperationException。换成普通的new ArrayList<>()就行。
  • 检查Movie的构造方法权限:如果Movie的构造方法是private或者包私有(没有修饰符),而你的测试类和Movie不在同一个包,那根本创建不了Movie实例,自然没法add。要么把构造方法改成public,要么把测试类移到和Movie相同的包下。
  • 检查集合是否未初始化:比如你在测试类里只声明了private List<Movie> movies;,但没在@Before或者@Test方法里初始化movies = new ArrayList<>();,这时候调用add()会抛NullPointerException,看起来像是方法用不了。
  • 检查JUnit依赖是否正常:如果是Maven/Gradle项目,看看依赖范围是不是设错了(比如Gradle用了compileOnly而不是testImplementation),或者依赖没同步。IDE里如果测试类有红色下划线,先解决编译问题再说。

问题2:编写JUnit测试用例测试DirectorComparator类

Comparator的核心是compare()方法,咱们要覆盖所有关键场景,下面给你具体的测试思路和代码示例:

首先明确要测试的场景:

  • 导演姓名首字母不同的排序逻辑
  • 导演姓名首字母相同,但后续字符不同的情况
  • 姓名大小写差异的处理(如果你的Comparator需要忽略大小写)
  • 导演姓名为null的边界情况(如果允许的话)
  • 实际用Comparator对集合排序后的结果是否符合预期

测试代码示例

import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.*;

public class DirectorComparatorTest {

    // 初始化Comparator实例,每个测试方法都能用
    private final DirectorComparator directorComparator = new DirectorComparator();

    @Test
    public void testCompare_DifferentFirstLetter() {
        // 准备测试数据:导演首字母C vs Q
        Movie inception = new Movie("Inception", "Christopher Nolan");
        Movie pulpFiction = new Movie("Pulp Fiction", "Quentin Tarantino");

        // C在字母表中早于Q,所以compare(inception, pulpFiction)应该返回负数
        int result = directorComparator.compare(inception, pulpFiction);
        assertTrue("Expected negative value when 'Christopher' comes before 'Quentin'", result < 0);

        // 反过来比较应该返回正数
        result = directorComparator.compare(pulpFiction, inception);
        assertTrue("Expected positive value when 'Quentin' comes after 'Christopher'", result > 0);
    }

    @Test
    public void testCompare_SameFirstLetter() {
        // 导演首字母都是J,比较后续字符:Cameron vs Gunn
        Movie avatar = new Movie("Avatar", "James Cameron");
        Movie guardians = new Movie("Guardians of the Galaxy", "James Gunn");

        // "Cameron"的首字母C早于"Gunn"的G,所以返回负数
        int result = directorComparator.compare(avatar, guardians);
        assertTrue("Expected negative value when 'Cameron' comes before 'Gunn'", result < 0);
    }

    @Test
    public void testCompare_IgnoreCaseHandling() {
        // 如果你的Comparator需要忽略大小写,测试这个场景
        Movie jurassicPark = new Movie("Jurassic Park", "steven spielberg");
        Movie schindlersList = new Movie("Schindler's List", "Steven Spielberg");

        // 忽略大小写的话,两个姓名应该相等,返回0
        int result = directorComparator.compare(jurassicPark, schindlersList);
        assertEquals("Expected equal when names are identical ignoring case", 0, result);
    }

    @Test(expected = NullPointerException.class)
    public void testCompare_NullDirector() {
        // 如果你的Comparator不处理null导演的情况,预期抛出空指针
        Movie unknownMovie = new Movie("Unknown", null);
        Movie inception = new Movie("Inception", "Christopher Nolan");

        directorComparator.compare(unknownMovie, inception);
    }

    @Test
    public void testSortingWholeList() {
        // 测试实际排序后的集合是否符合预期
        List<Movie> movies = new ArrayList<>();
        movies.add(new Movie("Pulp Fiction", "Quentin Tarantino"));
        movies.add(new Movie("Inception", "Christopher Nolan"));
        movies.add(new Movie("Avatar", "James Cameron"));

        // 用DirectorComparator排序
        Collections.sort(movies, directorComparator);

        // 验证排序顺序:Cameron(C) → Nolan(N) → Tarantino(Q)
        assertEquals("First movie should be Avatar", "Avatar", movies.get(0).getTitle());
        assertEquals("Second movie should be Inception", "Inception", movies.get(1).getTitle());
        assertEquals("Third movie should be Pulp Fiction", "Pulp Fiction", movies.get(2).getTitle());
    }
}

代码说明

  • 每个测试方法只测一个场景,保持单一职责,方便定位问题
  • 用assertTrue、assertEquals等断言来验证结果是否符合预期
  • 边界场景(比如null)一定要覆盖,避免线上出问题
  • 最后一个测试方法直接测试集合排序,更贴近实际业务场景

内容的提问来源于stack exchange,提问作者Leia_Organa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:35:32