我想爲一個靜態方法編寫一個單元測試,它需要一個類和方法名稱,並執行一些反射來調用具有參數的方法並存儲結果。我正在使用spring-boot
。如何根據springBoot的applicationContext單元測試方法?
當我運行完整套件時,我的測試實際上工作,但是當我作爲獨立運行測試時,它失敗。問題是我創建了一個模擬類(手寫模擬,不使用mockito
或easymock
),我希望使用靜態方法。但是,反射無法檢測到我的模擬類,因爲該類尚未被spring-boot
加載到applicationContext
中。下面是失敗行:
T proxy = SpringApplicationContext.getBean(clazz);
SpringApplicationContext定義:
@Component
public class SpringApplicationContext implements ApplicationContextAware
{
private static ApplicationContext applicationContext_;
@Override
public void setApplicationContext(ApplicationContext applicaitonContext) throws BeansException {
applicationContext_=applicaitonContext;
}
public static <T> T getBean(Class<T> requiredType) throws beanException {
return applicationContext_.getBean(requiredType);
}
*注意,我不得不手動重新輸入,請假設明顯的語法錯誤,錯別字。
所以基本上我的applicationContext
沒有被設置或定義。我只需要applicationContext
中的一個模擬bean,我可以手動完成,但是有更多spring
方法使用註釋嗎?
這聽起來像你溜得太快了[第11章](http://docs.spring.io/spring (當前)Spring文檔的/docs/current/spring-framework-reference/html/testing.html)!請仔細看看,特別是在[§11.3.4](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html#integration-testing-annotations)中,不要忘記:http://docs.spring.io/spring-batch/trunk/reference/html/testing.html,也許是一些示例:http://codesolid.com/spring-unit-testing-using-junit/ – xerx593