當Powermock遇到Spring

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);

Powermock與Spring有各的Classloader。當待測程式去load config產生對應的instance的時候,不曉得你是否有遇到下面的exception呢?

Caused by: java.lang.ClassCastException: com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl 
       cannot be cast to javax.xml.parsers.DocumentBuilderFactory
	at javax.xml.parsers.DocumentBuilderFactory.newInstance(DocumentBuilderFactory.java:123)
	at org.springframework.beans.factory.xml.DefaultDocumentLoader.createDocumentBuilderFactory(DefaultDocumentLoader.java:89)
	at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:70)
	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
	... 31 more

遇到這個問題我相信大家的做法應該和我差不多: 詢問好朋友Google! 我也相信大家應該有看到這兩篇12。很可惜的是: 它無法替你解決問題! 這兩篇提供的方法都是透過@PowerMockIgnore

@PowerMockIgnore("org.apache.xerces")              
@RunWith(PowerMockRunner.class)
@PrepareForTest(User.class)
public class MyTestClass { 
...
}

為什麼無法解決問題?你會發現Exception依然層出不窮,即使多加了PowerMockIgnore去消滅這些Exception,最終你會面對的是: WTF!你想要Mock的物件根本無法Mock! @PowerMockIgnore的用途是延遲Load你所設定的Class。但你想: 如果Spring延遲Load待測物件,這個物件用的ClassLoader會和PowerMock用的ClassLoader一樣嗎?結局是: 根本沒有Mock到!

來看看Spring的Source code吧! 從new ClassPathXmlApplicationContext(config)開始,到prepareBeanFactory時可以發現它會去Facotry的classLodaer。

public abstract class AbstractApplicationContext extends DefaultResourceLoader
		implements ConfigurableApplicationContext, DisposableBean {
	protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		// Tell the internal bean factory to use the context's class loader.
		beanFactory.setBeanClassLoader(getClassLoader());
 
                ...
	}
 
        ...
}

接著可以發現,在沒有設定ClassLodaer的情況下它會用ClassUtils.getDefaultClassLoader()。

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	public void setBeanClassLoader(ClassLoader beanClassLoader) {
		this.beanClassLoader = (beanClassLoader != null ? beanClassLoader : ClassUtils.getDefaultClassLoader());
	}
 
        ...
}

而在getDefaultClassLoader()中,可以發現它首先會取得currentThread的ClassLoader,最後才去使用它自身的ClassLoader。

	public static ClassLoader getDefaultClassLoader() {
		ClassLoader cl = null;
		try {
			cl = Thread.currentThread().getContextClassLoader();
		}
		catch (Throwable ex) {
			// Cannot access thread context ClassLoader - falling back to system class loader...
		}
		if (cl == null) {
			// No thread context class loader -> use class loader of this class.
			cl = ClassUtils.class.getClassLoader();
		}
		return cl;
	}

因此,在我們在透過Spring去Load Config產生Object之前,先去把目前的ClassLoader設定給current Thread不就解了嗎?

		Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);

但是,你別以為一切都天下太平了! 在很多的測試案例蹂躪下,最新錯誤: java.lang.OutOfMemoryError: PermGen space。

Powermock 1月中的Release號稱有解決這個問題。但經過測試並嘗試將log4j package加到PowerMockIgnore中依然無法解決問題。在這個issue中,也有其它user有OOM的問題。目前看來只能透過調高記憶體並等官方解決這個bug了。