java junit测试错误ClassCastException
在尝试运行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);
}
}
# 1 楼答案
你的工厂。getInstance方法返回一个Factory对象,而Factory不是IItemsService。也许你需要改变以下几点:
致:
# 2 楼答案
你调用了错误的方法。方法
Factory.getInstance()
返回一个实例(根据您的实现,它是单例的),因此当您将Factory
强制转换为IItemService
时,它将抛出一个ClassCastException
我在
Factory
中没有看到任何返回IItemService
的方法。这里唯一有意义的方法是getService
,它返回一个IService
。但是,如果您尝试将IService
强制转换为IItemService
,它可能会抛出ClassCastException
,并且IItemService不会扩展iSeries