2016-05-16 34 views
0

我寫了Junit測試類來測試特定的方法。在這個方法中處理的變量之一是彈簧注入,通過從屬性文件中獲取值。因彈簧注入導致Junit方法調用失敗

下面是我的測試方法

@Test 
public void myTestMethod() { 
    //invoking the method to be tested 
    Assert.assertTrue(updateGroceries()); 
} 

這是待測試的類,

public class ToBeTested { 

    //Spring injected value 
    String categories; 

    public boolean updateGroceries() { 
    List<String> categoryList = StringUtils.convertStringToList(categories); 
    } 

在上述類,類變量是彈簧注入。 這是屬性文件內容:

categories = Dals,Pulses,Dry Fruits,Edible Oil 

現在運行我Junit的方法,同時,執行失敗,因爲依賴注入是failing.Since我想在Tomcat測試運行的代碼。我想在不運行tomcat的情況下測試代碼。請提出一些解決方案。

回答

0

你應該看看Mockito。當你使用mockito框架時,你可以爲彈簧注入值創建模擬。你應該閱讀更多關於mockito website

1

首先要運行mockito,你需要在你的測試中啓用它。 使用註釋@RunWith(MockitoJunitRunner.class)或在測試開始時執行Mockito.initMocks()。 那麼您的測試應該是這樣的:

@RunWith(MockitoJunitRunner.class) 
private YourTest{ 

    @InjectMocks 
    ToBeTested toBeTested; 

    @Mock 
    ToBeTestedDependency dependency; 

    @Before 
    public void setUp(){ 
     ReflectionTestUtils.setField(toBeTested, "categories", 
      "someCategory"); 
    } 

    @Test 
    public void shouldDoThisOrThat(){ 
     toBeTested.updateCategories(); 
    } 
} 

不幸的Mockito不支持注射@Value標註的字段。您需要使用ReflectionTestUtils或設置運行您的測試與SpringJUnit4ClassRunner您需要定義您的彈簧上下文與PropertyPlaceholder配置解決作爲您的Value密鑰的財產。在那裏你可以找到參考documentation and example的春季測試方法。

希望這有助於。

相關問題