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

如何为对象列表关键词搜索方法编写单元测试及排查测试失败

图书馆应用搜索方法测试问题

问题背景

我开发了一个Library应用,正在为其中的方法编写测试。待搜索的书籍列表包含title、author和ISBN编号。ISBN搜索方法的测试正常,但title和author搜索测试失败——测试把搜索字符串和列表中的整个Book对象对比,而不是和title字符串对比。

被测试的方法

public ArrayList<Book> searchByTitle(String termToFind)
{
    ArrayList<Book> booksToReturn = new ArrayList<>();

    for (Book book : bookshelf)
    {
        if (book.getTitle().contains(termToFind))
        {
            booksToReturn.add(book);
        }
    }

    return booksToReturn;
}

测试代码

@Test
public void testLibrary_searchTitle()
{
    assertEquals("Shutter Island", library1.searchByTitle("Shutter Island"));
}

错误信息

expected: < Shutter Island > but was: <[Shutter Island by Dennis Lehane. ISBN: 2003003]>

问题分析与修正方案

  • 问题根源:searchByTitle返回的是存储Book对象的ArrayList,但你的测试直接用字符串和这个列表做对比,既存在类型不匹配,也不符合方法的返回逻辑。
  • 正确的测试逻辑应该分两步:
    1. 验证搜索结果列表的长度是否符合预期(比如找到1本匹配书籍);
    2. 从列表中取出具体的Book对象,验证其title属性是否等于目标字符串。

修正后的测试代码示例:

@Test
public void testLibrary_searchTitle()
{
    ArrayList<Book> searchResults = library1.searchByTitle("Shutter Island");
    
    // 确认找到1本匹配的书
    assertEquals(1, searchResults.size());
    
    // 验证该书的title正确
    Book foundBook = searchResults.get(0);
    assertEquals("Shutter Island", foundBook.getTitle());
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 17:37:03