2017-10-20 32 views
1

我正在嘗試爲我創建的彈簧服務應用程序編寫JUnit測試用例。我已經完成了對應用程序的煙霧測試,並正在編寫一系列向前推進的單元測試。使用自動佈線組件編寫Spring引導服務應用程序的JUnit測試用例

我開始測試服務層。我遇到了一個與我的@AutoWired組件有關的問題,包括我的DAO對象。運行Spring應用程序本身時,一切正常。但是,運行我的JUnit測試時,它們不會自動裝入並保持爲空,從而導致NPE。以下是我與工作的骨架:

服務文件:

@Component 
public class WebServiceImpl implements WebService{ 

@Autowired 
WebDAO webDAO; 

@Override 
public List<String> getItems(){ 
    List<String> items = webDAO.getItems(); 
    /* 
    * some filtering/actions done here 
    */ 
    return items; 
    } 
} 

測試文件:

@RunWith(SpringRunner.class) 
@SpringBootTest 
public class ServiceTests{ 
    private WebService service; 

    @Before 
    public void setup(){ 
     this.service = new WebServiceImpl(); 
    } 

    @Test 
    public void getItemsTest(){ 
     List<String> items = this.service.getItems(); 
     assertNotNull(items); 
    } 
} 

當運行這個測試我從webDAO的NPE。它不像春季啓動啓動時那樣自動裝配。我是新來的工作春天,所以我不知道最好的方式進行。我認爲這沒有自動裝配,因爲我沒有像通常那樣啓動應用程序,而是直接實例化類。

我唯一可能的想法是爲了測試的唯一目的而創建一個dao的getter/setter;但是我必須爲每個使用的自動佈線域和Idk做到這一點,如果它會有任何不需要的結果。

回答

2

您將被測組件自動裝入測試。

您正在Spring容器之外創建組件,因此它不知道該組件。

private WebService service; 

    @Before 
    public void setup(){ 
     this.service = new WebServiceImpl(); 
    } 

應該只是

@Autowired 
private WebService service; 
+0

啊,新手的錯誤。感謝您花時間回答! – Aweava

相關問題