2017-07-19 48 views
0

我有一個讀取資源文件的類方法,但是當我試圖用單元測試運行這個類時,找不到文件。找不到來自UnitTest的ClassLoader資源

如果我要部署應用程序戰爭或只是使用maven從eclipse運行它,一切正常。

文件位置(不知道是否需要的src /測試/資源,增加它後,才遇到的問題,但並沒有幫助):

src/main/resources/ 
    -> com 
     -> xxxx 
      -> xxxx_portal 
       -> web 
        -> server 
         -> servlet 
          -> reports -> Logo.png 
src/test/resources/ 
    -> com 
     -> xxxx 
      -> xxxx_portal 
       -> web 
        -> server 
         -> servlet 
          -> reports -> Logo.png 

相關類代碼:

package com.xxxx.xxxx_portal.web.server.servlet.reports; 

public class ModuleReports { 
    private static final String LOGO_IMAGE_PATH = "/com/xxxx/xxxx_portal/web/server/servlet/reports/Logo.png"; 

    ... 
    private static InputStream getLogoImage() { 
     ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 
     InputStream is = classLoader.getResourceAsStream(LOGO_IMAGE_PATH); //Problem here, InputStream is null. It should not be null. 
     return is; 
    } 
    ... 
} 

回答

0

ClassLoader.getResourceAsStream的參數不能以斜槓開頭(/)。雖然你可以只從ACDLABS_LOGO_IMAGE_PATH的值刪除初始斜線,你應該使用Class.getResourceAsStream而不是ClassLoader.getResourceAsStream:

private static InputStream getLogoImage() { 
    return ModuleReports.class.getResourceAsStream("ACDLogo.png"); 
} 

不像ClassLoader.getResourceAsStream,該參數Class.getResourceAsStream 可以先從斜線,但不需要。如果沒有,則假定該字符串指向與其被調用的類相同的包中的資源。所有這些行爲在the documentation中描述。

+0

如果可能的話,我希望不要碰這個類及其方法。你是否說刪除斜槓將使單元測試工作?正如我所說的,Class ModuleReports在沒有從單元測試運行時可以正常工作。 – CrazySabbath

+0

值得一試。您可能還想更新您的問題並顯示您的應用程序的構建方式;也就是說,顯示Maven pom.xml或Ant build.xml。 – VGR

+0

刪除斜槓工程。雖然這是一個奇怪的行爲,因爲部署的應用程序工作正常(無論是否啓動斜線),而單元測試僅在刪除開始斜線時才起作用。 – CrazySabbath