Ethan R
Ethan R

Reputation: 11

How to create a unit test for a method searching keywords within a list of objects?

I have a Library application and am trying to create tests for the methods in it. The books in the list being searched consist of a title, author, and ISBN number. The tests for the ISBN search method work, but the title and author search tests are failing. The test is comparing the string being searched with the entire object in the list instead of the title string.

The method that is being tested:


    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;
    }

The test I have written:

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

    }

The error I am receiving:

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

Upvotes: 0

Views: 217

Answers (1)

ajc2000
ajc2000

Reputation: 834

In your assertEquals comparison, you are comparing the expected title, which is a String, to an ArrayList of Book objects, rather than the title of (presumably) the single book that is meant to be returned.

Since your library method returns an ArrayList, so you'll need to get the first entry of that List. You probably want to make sure the list is non-empty before you do this. Then, you'll want to compare the expected title to the actual book's title rather than to the entire Book object.

ArrayList<Book> bookList = library1.searchByTitle("Shutter Island");
assertEquals(1, bookList.size());
assertEquals("Shutter Island", bookList.get(0).getTitle());

Alternatively, if your Book class has an easily usable constructor and a properly implemented equals method, you can construct the expected Book object itself to compare the Book object returned by your library method, ensuring all Book properties match as expected.

Book expectedBook = // your code here
ArrayList<Book> bookList = library1.searchByTitle("Shutter Island");
assertEquals(1, bookList.size());
assertEquals(expectedBook, bookList.get(0));

Upvotes: 2

Related Questions