2012-02-09 33 views
2

我正在使用spring 3 mvc/security框架。在不使用@RunWith的情況下在Spring單元測試中連接依賴關係

我已經創建了一個Controller類,它具有對從中加載數據的存儲庫的引用。該類用@Controller進行註釋,存儲庫類用@Repository進行註釋,並且存儲庫的實例爲@Autowired

但是當我嘗試單元測試時,autowired實例會拋出一個空指針異常。

現在,我明白了,因爲它是自動裝配的,它需要在春天的環境中被挑選出來。但我覺得如果我使用@RunsWith()那麼它就成爲一個綜合測試。我真的很想分開集成測試(使用@RunsWith)和單元測試。關於如何解決這個空指針異常的任何想法?只想創造我的控制器類的getter/setter方法是好的?:

庫類:

@Repository 
public class Repository{ 
.... 
} 

控制器類:

@Controller 
public class Controller{ 
@Autowired 
private Repository repo; 
.... 
public String showView(){ 
    repo.doSomething(); 
} 

測試類:

public ControllerTest { 
@Test 
public shouldDoTestOfShowView(){ 
} 
} 
+0

那麼在控制器中創建getter/setter是最佳實踐嗎? – 2012-02-09 15:02:43

回答

3

我個人傾向於使用@Simon's approach,而不是暴露setter方法,雖然這兩種方法是罰款。雖然爲了測試而添加setter是有點煩人的。

另一種方法是使用Spring's ReflectionTestUtils class直接使用反射來將依賴關係戳到字段中,從而不需要特殊的構造函數和設置器,例如,

public ControllerTest { 
    @Test 
    public shouldDoTestOfShowView() { 
     Controller controller = new Controller(); 
     Repository repository = new Repository(); 

     ReflectionTestUtils.setField(controller, "repo", repository); 
    } 
} 

是否仍然構成「整合測試」是你的電話(我不知道)。

+0

我認爲reflectionTestUtils可能是我最好的選擇。但在我的情況下,我的回購有一個autowired entityManager,所以我將不得不弄清楚如何做嵌套反射。 – 2012-02-09 15:44:38

+3

如果你正在做單元測試,你應該嘲笑倉庫。 – 2012-02-09 15:47:05

0

常,我會提供setter只是爲了測試目的,但如果你關心你的代碼使用的消費者不正確的,也許你想用一種利用反射的方法。

我在過去編寫了一個實用程序,它接受兩個參數,一個目標對象和一個目標對象。

public static void set(Object target, Object setMeOnTarget) { 
    // 
} 

你可以從這裏做的是反思對target領域,尋找春天的支持自動裝配註解(@Autowired@Resource@Inject,甚至@Value),看看是否setMeOnTarget可以分配到該字段(我使用Class.isAssignableFrom(Class))。

它可能有點脆弱(Spring突然停止支持這些註釋...不太可能......),但它對我來說非常有用。

2

我總是寫2個構造函數。一個沒有Spring的參數,一個是受保護的,有單元測試的所有依賴。

@Controller 
public class Controller{ 
@Autowired 
private Repository repo; 

public Controller() { 
    super(); 
} 

protected Controller(Repositoy repo) { 
    this(); 
    this.repo = repo; 
} 
+0

爲什麼不只有一個@Autowired構造函數?而不是使用現場級自動裝配? – 2012-02-09 15:36:02

+1

如果您使用XML配置,那麼您只能使用1個帶@Autowired的構造函數。如果你使用基於Java的配置,你必須在Java中實例化這個類,並且有一個空的構造函數是很方便的。 – 2012-02-09 15:40:45

相關問題