Java junit测试错误-ClassCastException
在尝试运行junit测试时,我遇到以下错误-Java junit测试错误-ClassCastException,java,junit,Java,Junit,在尝试运行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
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);
}
}
公共类工厂{
私有工厂(){}
私有静态工厂=新工厂();
公共静态工厂getInstance(){return Factory;}
公共静态IService getService(字符串serviceName)引发ServiceLoadException{
试一试{
Class c=Class.forName(getImplName(serviceName));
返回(IService)c.newInstance();
}捕获(例外e){
抛出新的ServiceLoadException(serviceName+“未加载”);
}
}
私有静态字符串getImplName(字符串serviceName)引发异常{
java.util.Properties=new java.util.Properties();
java.io.FileInputStream fis=new java.io.FileInputStream(“config\\application.properties”);
道具载荷(fis);
fis.close();
返回props.getProperty(serviceName);
}
}
您的Factory.getInstance方法返回一个Factory对象,而Factory不是IItemsService。也许您需要更改以下内容:
@SuppressWarnings("static-access")
IItemsService getItem = (IItemsService)factory.getInstance();
致:
您调用了错误的方法。方法
Factory.getInstance()
返回一个实例(根据您的实现,它是单实例),因此当您将Factory
强制转换为IItemService
时,它将抛出一个ClassCastException
我在您的
工厂中没有看到任何返回IItemService
的方法。这里唯一有意义的方法是getService
,它返回一个IService
。但是,如果您尝试将iDevice
强制转换为IItemService
并且IItemService不扩展iDevice,它可能会抛出ClassCastException
。什么是方法Factory.getInstance()
类似?它似乎返回一个工厂
对象,但是IItemsService
。
@SuppressWarnings("static-access")
IItemsService getItem = (IItemsService)factory.getService(serviceName);