2015-06-27 37 views
1

我有類構造函數獲取輸入,如:Java測試構造函數使用不同的參數

public class Project { 
    public Project(Parameter1 par1, Parameter2 par2 ...) { 
    //here if one incoming parameters equals null - throw exception 
    } 
} 

的問題是我怎麼能測試異常一個測試中拋出不同的參數?喜歡的東西:

@Test 
publci void testException() { 
    Project project1 = new Project(null, par2 ....);//here it throws exception and test is finished((((
//I want it to continue testing project2 
    Project project2 = new Project(par1, null ...); 
} 
+0

這看起來我的權利。它對你造成了什麼問題? –

+0

我的班級有5個參數輸入承包商。我想在一次測試中測試它們。 project2,project3等等。不要一開始就停下來,但要確保在所有情況下Project都會拋出異常。這就是問題。 – ovod

+0

我不確定這是可能的。通常,你會發現你需要多次測試才能完全測試一個函數。 –

回答

1

保持Project1 = new Project(....Project2 = new Project(.....以個人嘗試catch塊。通過第一個塊拋出的異常不會停止稍後要運行的代碼段。

3
@Test 
public void testException() { 
    boolean exception1Thrown = false; 
    try { 
     Project project1 = new Project(null, par2 ....); 
    }catch(Exception e){ 
     exception1Thrown = true; 
    } 
    assertTrue(exception1Thrown); 

    boolean exception2Thrown = false; 
    try { 
     Project project2 = new Project(par1, null ...); 
    }catch(Exception e){ 
     exception2Thrown = true; 
    } 
    assertTrue(exception2Thrown); 

} 

這只是其中的幾種方法之一。有關更多信息,請參見this question

0

您可以將它傳遞標誌(shouldThrowException)作爲測試參數之一。但更簡潔的方法是做兩個測試。一個用於正確的參數,一個用於錯誤的參數。我這樣做:

import static org.assertj.core.api.Assertions.assertThatThrownBy; 
import org.junit.runner.RunWith; 
import com.googlecode.zohhak.api.Coercion; 
import com.googlecode.zohhak.api.TestWith; 
import com.googlecode.zohhak.api.runners.ZohhakRunner; 

@RunWith(ZohhakRunner.class) 
public class MyTest { 

    @TestWith({ 
     "parameter1,  parameter2", 
     "otherParameter1, otherParameter2" 
    }) 
    public void should_construct_project(Parameter parameter1, Parameter parameter2) { 
    new Project(parameter1, parameter2); 
    } 

    @TestWith({ 
     "null,   parameter2", 
     "otherParameter1, null", 
     "badParameter1, goodParameter2" 
    }) 
    public void should_fail_constructing_project(Parameter parameter1, Parameter parameter2) { 

    assertThatThrownBy(() -> new Project(parameter1, parameter2)) 
            .isInstanceOf(NullPointerException.class);   
    } 

    @Coercion 
    public Parameter toParameter(String input) { 
    return new Parameter(...); 
    } 
} 

的情況下,要測試所有可能的參數組合,則數據提供商或理論可能是有用的。

0

您可以使用https://github.com/Pragmatists/JUnitParams做到這一點:

假設你有一個Person對象是所有的參數必須指定,那麼你可以通過這種方式測試與JUnitParams:

@Test(expected = IllegalArgumentException.class) 
    @Parameters(
    {", bloggs, [email protected]", 
    "joe, , [email protected],", 
    "joe, bloggs, ,", 
) 
public void allParametersAreMandatory(String firstName, String lastName, String emailAddress) 
{ 
    new Person(firstName, lastName, emailAddress); 
}