1

我有一個集成測試,執行以下操作:自動裝配在Spring TestContext框架

@ContextConfiguration(locations={..path to xmls..}) 
class IntegTestBase{ 

    --- some field initializations; --- 
} 

class MyIntegTest extends IntegTestBase{ 

    @Test 
    public testingMethod(){ 
     MyClass obj = new MyClass(); 
     obj.methodToBeTested(); 

     ---- some assertions ---- 
    } 
} 

class MyClass{ 

    @Autowired 
    Something obj1; 

    public int methodToBeTested(){ 

     --- Somecode --- 
    } 
} 

在上面的代碼中,我想,當測試用例運行MyClass的對象將創建的所有字段將被自動裝配。但是當測試運行時,所有自動裝配的字段都是空的。它沒有抱怨無法找到bean定義,所以我假設測試上下文在這裏是可見的。但我不明白爲什麼它沒有接線。另一方面,我可以在測試類中創建這些字段,自動裝載它們並將其設置爲創建的對象。有人可以告訴爲什麼這些字段爲空嗎?

回答

3

你正在創建使用new運營商的Spring bean:

MyClass obj = new MyClass(); 

這幾乎從未工程。您需要詢問Spring容器以提供MyClass bean的完全可操作的初始化實例,例如,與你的測試用例中自動裝配/ DI:

@ContextConfiguration(locations={..path to xmls..}) 
class IntegTestBase{ 

    @Autowired 
    protected MyClass obj; 

} 

在測試之後簡單地使用它:

@Test 
public testingMethod(){ 
    //don't recreate `obj` here! 
    obj.methodToBeTested(); 

    ---- some assertions ---- 
} 

事實上,這是Spring測試支持提供的功能。您還必須記住,如果MyClass是單身人士,則obj將在每次測試中指向完全相同的實例,但這通常不是問題。

理論上可以用完整的AspectJ,但你不想走這條路。

1

MyClass春豆嗎?如果是這種情況,您應該自己創建一個實例(使用new),但它的@Autowired與其他任何依賴關係一樣,例如而不是

class MyIntegTest extends IntegTestBase{ 

    @Autowired 
    MyClass obj; 

    @Test 
    public testingMethod(){ 
     obj.methodToBeTested(); 
     // ... 
    } 
}