2014-10-27 212 views
0

我正在嘗試爲繼承的基於Spring的項目配置單元測試。我嘗試了一些東西,但基本上我試圖將@Autowired的東西塞進我的測試用例中。這裏是我的設置:「簡單」彈簧單元測試

控制器類,看起來像這樣:

@Controller("serverService") 
@RequestMapping("/rest/server") 
@Api(value = "server") 
public class ServerServiceImpl extends AbstractServiceImpl implements ServerService { 
    @Override 
    @RequestMapping(value = "/getTime", method = RequestMethod.GET) 
    public @ResponseBody 
    GatewayResponse<TimeData> getTime() {...} 

ServerService僅僅是能夠互操作與GWT的接口。我現在不太擔心GWT的單元測試。

AbstractServiceImpl的主要目的是包裝一個基於SOAP的Web服務,該服務器本質上是代理服務器,使移動友好。網絡服務由Apache CXF自動生成。 AbstractServiceImpl如下(大約):

public class AbstractServiceImpl { 
    @Autowired 
    private WebServices webServices; 

    public WebServices getWebServices() { 
     return webServices; 
    } 

在我的測試類,我有:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = {"classpath:**/applicationContext.xml", "classpath:**/applicationContext-Services.xml"}) 
@WebAppConfiguration 
public class LoginTest { 
    @Autowired 
    private ServerServiceImpl svc; 

    public LoginTest() { 
    } 

    @Test 
    public void validate() { 
     assertNotNull(svc); 
    } 
} 

我在努力與模擬JSON和這樣的模擬電話到我的web服務沒有興趣。我只想編寫單元測試,創建未嘲笑的ServerServiceImpl與未嘲笑的WebServices對象並調用實時服務器。

我的測試目前失敗,因爲@Autowired無法創建ServerServiceImpl。我也嘗試重構我的代碼,使用@Autowired作爲WebServices,並使用它傳遞給構造函數ServerServiceImpl,但這也由於@Autowired而失敗。

+0

是applicationContext.xml的文本中的類路徑或只是你活的? – tom 2014-10-27 23:50:36

+0

我只有一個applicationContext.xml,所以我認爲這必須是活的......除非有些魔法/彈簧魔法以某種方式創建另一個。 – Tim 2014-10-27 23:51:33

+0

要單元測試這些,請使用構造函數注入和一個模擬庫(如Mockito)。這可以讓你完全避免使用Spring,並且在沒有外部依賴的情況下單獨測試這個類。 – chrylis 2014-10-28 00:08:37

回答

0

原來這很簡單。如果你指定一個應用程序上下文不存在的路徑Spring會拋出錯誤,例如:

@ContextConfiguration("classpath:does-not-exist.xml") 

以上將創建一個漂亮的簡單的錯誤信息,告訴你問題是什麼,也就是找不到文件的異常。另一方面,這段代碼不會:

@ContextConfiguration("classpath:**/does-not-exist.xml") 

所以我的問題是,簡單地說,Spring找不到應用程序上下文XML。最後我做了現場上下文的副本,在src/test/resources扔它,並更新了我的pom.xmlsurefire-plugin@ContextConfiguration如下:

<addtionalClasspathElements> 
    <addtionalClasspathElement>${basedir}/src/test/resources</addtionalClasspathElement> 
</addtionalClasspathElements> 

@ContextConfiguration(locations = { "classpath:applicationContext.xml", "classpath:applicationContext-Services.xml" }) 
相關問題