-1

尝试运行 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);
}
}
4

2 回答 2

0

您的 Factory.getInstance 方法返回一个 Factory 对象,而 Factory 不是 IItemsService。也许您需要更改以下内容:

@SuppressWarnings("static-access")
IItemsService getItem = (IItemsService)factory.getInstance();

至:

@SuppressWarnings("static-access")
IItemsService getItem = (IItemsService)factory.getService(serviceName);
于 2012-06-17T03:17:42.843 回答
0

你调用了错误的方法。该方法Factory.getInstance()返回一个实例(根据您的实现它是单例的),因此ClassCastException当您Factory转换为IItemService.

我在你的Factory那个 return中没有看到任何方法IItemService。这里唯一有意义的方法是getService返回一个IService. 但是,ClassCastException如果您尝试强制IService转换IItemService并且 IItemService 没有扩展 IService,它可能会抛出。

于 2012-06-17T05:11:45.540 回答