I have an interface test class that implements another super-class. In the test class I have a method that is supposed to update an object from an array list; first it's supposed to check if the objects is in the list, if it is, it will delete and add a new object (replace). If it cant find the object it will throw an exception message. Here is the code I have implemented:
public class ProductDBImpl implements ProductDB {
// field declarations
ArrayList<Product> products = new ArrayList<Product>();
@Override
public void updateProduct(Product product) throws ProductNotFoundException
{
// TODO Auto-generated method stub
Iterator<Product> pritr = products.iterator();
while(pritr.hasNext())
{
Product pr = pritr.next();
if (!pr.getId().equals(product.getId()))
{
throw new ProductNotFoundException("Product does no exist");
}
pritr.remove();
}
products.add(product);
}
First off I dont know if this is the correct way to do it. And, when I test it with my test client script, I get an error that reads:
Exception in thread "main" productdb.util.AssertionFailedError: should've gotten ProductNotFoundException
The code for the test client is as follows:
ipod.setId(Integer.MAX_VALUE);
try {
productDB.updateProduct(ipod);
Assert.fail("should've gotten ProductNotFoundException");
} catch (ProductNotFoundException pnfe) {
// expecting this
}
Please help me identify my error. Thanks.
LATEST EDIT I updated my code based on the feedback I was getting RE the first item throwing the error:
public void updateProduct(Product product) throws ProductNotFoundException
{
// TODO Auto-generated method stub
Iterator<Product> pritr = products.iterator();
while(pritr.hasNext())
{
Product pr = pritr.next();
System.out.println(pr.getId());
System.out.println(product.getId());
if (pr.getId().equals(product.getId()))
{
pritr.remove();
}
else
{
throw new ProductNotFoundException("Product Not Found");
}
}
products.add(product);
}
ANOTHER UPDATE
public void updateProduct(Product product) throws ProductNotFoundException
{
// TODO Auto-generated method stub
Iterator<Product> pritr = products.iterator();
boolean match = true;
while(pritr.hasNext())
{
Product pr = pritr.next();
if (pr.getId().equals(product.getId()))
{
pritr.remove();
}
else
{
match = false;
}
}
if (match == false)
{
new ProductNotFoundException("Product not found");
}
else
{
products.add(product);
}
}