模拟bean时的类强制转换异常

时间:2014-12-12 07:24:10

标签: spring unit-testing testng

我正在尝试使用powermock和TestNG在我的应用程序中创建测试用例。这是一个Web应用程序,弹出上下文xml通过web.xml加载。我想用我自己的测试xml模拟spring上下文xml并从那里访问bean。

ContextLoader代码

 public class AppContextLoader implements ApplicationContextAware {

  private static ApplicationContext context;

  public void setApplicationContext(ApplicationContext context) {
      this.context = context;
  }

  public static Object getBean(String beanName) {
      return context.getBean(beanName);
  }
}

我试图稍后在我的代码中访问bean,如下所示

    XMLConverter converter = (XMLConverter) AppContextLoader.getBean("XMLConverter");

以下是我的测试代码

@PrepareForTest(AppContextLoader.class)
@PowerMockIgnore({"javax.management.*", "javax.xml.*","org.xml.*","org.w3c.dom.*"})
public class ImplTest {

Impl impl;
ApplicationContext context;

   @ObjectFactory
   /**
    * Configure TestNG to use the PowerMock object factory.
    */
   public IObjectFactory getObjectFactory() {
      return new org.powermock.modules.testng.PowerMockObjectFactory();
   }

@BeforeClass
public void setUp() throws Exception {
     impl = new Impl();
     context = new ClassPathXmlApplicationContext("Test_config.xml");

}

@Test
public void execute() {

    try {
            PowerMock.mockStatic(AppContextLoader.class);
            expect(AppContextLoader.getBean("XMLConverter")).andReturn(context.getBean("XMLConverter"));
            PowerMock.replay(AppContextLoader.class);

            actualResponse = impl.execute(request, "");
            //PowerMock.verify(AppContextLoader.class);

            Assert.assertEquals("", actualResponse);


    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}

当我执行此代码时,我收到以下错误:

java.lang.ClassCastException:com.xxx.xxx.xxx.xxx.bean.XMLConverter无法强制转换为com.xxx.xxx.xxx.xxx.bean.XMLConverter

我是单元测试的新手,并且不确定导致此问题的原因是同一个类无法互相投射。任何帮助将不胜感激

0 个答案:

没有答案