In: Computer Science
I am doing a lab and I get this error message in my unittest: junit.framework.AssertionFailedError: Hint: matches() should have returned true when item matches the item passed into IdLookup constructor. Here is my code. What changes should be made?
/**
* This class is a lookup that matches items whose id matches
exactly
* a specified id, to be passed into the constructor when
creating
* the instance of the lookup.
*
* @author Franklin University
* @version 2.0
*/
public class IdLookup implements Lookup
{
private String lookupId;
/**
* Constructor for objects of class IdLookup.
* @param id the id to lookup.
*/
public IdLookup(String id)
{
lookupId = id;
}
/**
* Indicates whether the item's id exactly matches the id
* passed into the contructor.
* @param item the item being checked for a match.
* @return true if the id of the item matches, otherwise
* false.
*/
@Override
public boolean matches(Item item)
{
if (item == null) {
return false;
}
return lookupId == item.getId();
}
}
Here is the corrected code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
Note: You did not provide Lookup interface, or Item class, so I can only assume that everything else is working correctly and getId method of Item class returns a String. Your mistake was to use == operator to compare Strings which you should never do in order to compare their contents. For that, you should use equals() method. The reason is explained in comments.
public class IdLookup implements Lookup {
private String lookupId;
/**
* Constructor for objects of class IdLookup.
*
* @param id
* the id to lookup.
*/
public IdLookup(String id)
{
lookupId = id;
}
/**
* Indicates whether the item's id exactly matches the id passed into the
* contructor.
*
* @param item
* the item being checked for a match.
* @return true if the id of the item matches, otherwise false.
*/
@Override
public boolean matches(Item item) {
if (item == null) {
return false;
}
// assuming getId returns a String
// you should use equals() method to compare two Strings, never use ==.
// In case of Strings, == returns true only if the two objects have same
// memory (i.e the two String objects being compared refer to the same
// address in memory). equals() method returns true if two Strings have
// same contents regardless of their memory address.
return lookupId.equals(item.getId());
}
}