2016-03-05 51 views
1

你能幫助我嗎? 我有50場(一個字符串,整數b ...)的對象,我有這樣的「如果」語句的方法:單元測試 - 一種方法而不是50

if(a==null OR b==null OR ...(for any field)) { 
throw My Exception(); 
} 

我寫單元測試這種方法。我創建了對象的實例50這樣

1. a=null, <-- only a is null for this instantiation 
2. b=null <--- only b is null for this instantiation 
     . 
     . 
     . 
50. n=null <--- only n is null for this instantiation 

我的問題是,我必須寫這50種@Test方法?

我寫了一個這樣的@Test方法,但我不確定這是否正確根據單元測試的範例。

@Test 
public void test(){  
    for(int a=0;a<50;a++){  
    try{  
     //I call the method with my if statament for any of 50 object 
     } 
     catch(MyException e){ 
     y++; 
     } 
    }  
Assert.assert(y,50);  
} 
+3

「我有100個領域的對象」 - 難道這是你真正的問題嗎? –

+3

如果你有一個包含100個字段的對象,那麼你沒有寫出面向對象的軟件。 –

+1

燒掉所有東西然後重新開始? –

回答

1

我正在使用JUnit 4參數化測試編寫答案。由於您已經創建了100個不同的對象實例,只需將該代碼放入parameters方法即可。

@RunWith(Parameterized.class) 
public class MyParameterizedTest { 

    MyObject value; 

    public MyParameterizedTest(MyObject value) { 
     this.value = value; 
    } 

    @Parameterized.Parameters 
    public static List<MyObject> parameters() { 
     // create a list with 100 different instances of your object... 
     // return it... 
    } 

    @Test(expected = MyException.class) 
    public void testMethodCallShouldThrowException() throws MyException { 
     // I call the method with my if statament for any of 100 object 
     myMethod(value); 
    } 
} 

鏈接到文檔:Parameterized

+0

以這種方式斷言異常的替代方法:http://stackoverflow.com/a/35813323/360211 – weston

+0

我認爲這是我正在尋找的解決方案。我會嘗試。謝謝。 – user3740179

1

這可能不是你想聽到的答案,但有意義的單元測試的前提是合理的設計。擁有100個屬性的類肯定是​​一個可以改進的設計。

所以考慮重新設計你的班級。

編輯:乍一看,我的聲明似乎與測試驅動設計方法相矛盾,您可以在未實施類的情況下實施單元測試。但是,結果這可能會阻止你結束100場的課程。所以這不是矛盾。