junit test error - ClassCastException
- by Josepth Vodary
When trying to run a junit test I get the following error -
java.lang.ClassCastException: business.Factory cannot be cast to services.itemservice.IItemsService
at business.ItemManager.get(ItemManager.java:56)
at business.ItemMgrTest.testGet(ItemMgrTest.java:49)
The specific test that is causing the problem is
@Test
public void testGet() {
Assert.assertTrue(itemmgr.get(items));
}
The code it is testing is...
public boolean get(Items item) {
boolean gotItems = false;
Factory factory = Factory.getInstance();
@SuppressWarnings("static-access")
IItemsService getItem = (IItemsService)factory.getInstance();
try {
getItem.getItems("pens", 15, "red", "gel");
gotItems = true;
} catch (ItemNotFoundException e) {
// catch
e.printStackTrace();
System.out.println("Error - Item Not Found");
}
return gotItems;
}
The test to store items, which is nearly identical, works just fine...
The factory class is..
public class Factory {
private Factory() {}
private static Factory Factory = new Factory();
public static Factory getInstance() {return Factory;}
public static IService getService(String serviceName) throws ServiceLoadException {
try {
Class<?> c = Class.forName(getImplName(serviceName));
return (IService)c.newInstance();
} catch (Exception e) {
throw new ServiceLoadException(serviceName + "not loaded");
}
}
private static String getImplName (String serviceName) throws Exception {
java.util.Properties props = new java.util.Properties();
java.io.FileInputStream fis = new java.io.FileInputStream("config\\application.properties");
props.load(fis);
fis.close();
return props.getProperty(serviceName);
}
}