junit测试错误 - ClassCastException

时间:2012-06-17 03:02:37

标签: 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 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);
}
}

2 个答案:

答案 0 :(得分:0)

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

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

为:

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

答案 1 :(得分:0)

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

我在Factory中看不到任何返回IItemService的方法。唯一有意义的方法是getService返回IService。但是如果你试图将ClassCastException强制转换为IService并且IItemService不扩展IService,它可能会抛出IItemService