2012-08-02 96 views
2

我和春天3.0和JUnit 4.8工作時,我試圖開發一些單元測試。春天依賴注入空運行測試用例

其實,我只是想設置使用依賴注入的測試用例通過了JUnit使用的應用程序上下文加載XML definined一個bean的屬性(文件)。

我使用的註釋爲JUnit 4中的形式給出了加載XML文件配置。這是主要的BaseTest所使用的所有測試類:

@ContextConfiguration("/test-context.xml") 
@RunWith(SpringJUnit4ClassRunner.class) 
@Ignore 
public class BaseTest { ... } 

這是的test-context.xml

<context:component-scan base-package="com.test" /> 

<bean id="ExtractorTest" class="com.test.service.ExtractorTest"> 
    <property name="file" value="classpath:xls/SimpleFile.xls"></property> 
</bean> 

一個部分,因此我想要在我的課上做與測試(ExtractorTest)只是通過在類路徑中加載文件來設置'文件'屬性,沒有別的。

下面是測試類的部分:

public class ExtractorTest extends BaseTest { 

    private Resource file; 
    private InputStream is; 

    public void setFile(Resource file) { 
     this.file = file; 
    } 

    @Before 
    public void init() { 
     this.is = this.getClass().getResourceAsStream("/xls/SimpleFile.xls"); 
     Assert.assertNotNull(is); 
    } 

    @Test 
    public void testLoadExcel() throws IOException { 
     // file is always null, but the InputStream (is) isn't! 
     Assert.assertNotNull(file.getFile()); 
     InputStream is = new FileInputStream(file.getFile()); 
     HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is)); 
     // todo... 
    } 

}

的問題是,二傳手的作品,因爲我已經添加了一個斷點,春天正在建立它的性質確定。但是當測試方法開始時它是空的,可能是因爲它是另一個正在運行的實例,但爲什麼?我如何設置要使用應用程序上下文的XML進行測試的'文件'加載?我無法使用jUnit分配它,但我不明白爲什麼以及如何去做。我試圖避免在@Before方法寫的,但我不知道它絕對是一個好辦法...

謝謝。

PD:對不起我的英語;-)

回答

3

您的配置不起作用,因爲春天不創建的ExtractorTest其中JUnit使用的實例;而是由JUnit創建實例,然後傳遞給Spring進行後期處理。

您所看到的效果是因爲應用程序上下文創建具有ID ExtractorTest豆,但從來沒有人使用了。

僞代碼:

ApplicationContect appContext = new ... 
appContext.defineBean("ExtractorTest", new ExtractorTest()); // Calls setter 

ExtractorTest test = new ExtractorTest(); // Doesn't call setter 
test.postProcess(appContext); // inject beans from appContext -> does nothing in your case 

因此,解決辦法是定義一個bean file

<bean id="file" class="..." /> 

(請參閱文檔如何建立一個Resource豆),然後讓Spring注入是:

@Autowired 
private Resource file; 
+0

謝謝阿龍! 這就像你說的。我不知道這是不是使用Spring和jUnit測試文件的最佳方法,因爲它代表了很多新的bean來定義(每個測試文件使用1個),但它是有效的。可能是更好的主意,可以在@Before方法中指定它... 無論如何,再次感謝你! – 2012-08-02 15:36:02