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]>
In your
assertEqualscomparison, you are comparing the expected title, which is aString, to an ArrayList ofBookobjects, 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
Bookobject.Alternatively, if your
Bookclass has an easily usable constructor and a properly implementedequalsmethod, you can construct the expectedBookobject itself to compare theBookobject returned by your library method, ensuring allBookproperties match as expected.