尝试运行 junit 测试时,出现以下错误 -
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)
导致问题的具体测试是
@Test
public void testGet() {
Assert.assertTrue(itemmgr.get(items));
}
它正在测试的代码是...
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;
}
存储项目的测试几乎相同,效果很好......
工厂类是..
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);
}
}