![](/img/trans.png)
[英]Factory in Java when concrete objects take different constructor parameters
[英]java test constructor with different parameters
我有構造函數的類,它得到像這樣的輸入:
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 ...);
}
@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);
}
那只是幾種方法之一。 看到這個問題更多
將Project1 = new Project(....
和Project2 = new Project(.....
保留在它們各自的try catch塊中。通過第一個塊引發的異常不會停止代碼的后續部分運行。
您可以通過將標記(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(...);
}
}
如果您想測試所有可能的參數組合,那么數據提供者或理論可能會有用。
您可以使用https://github.com/Pragmatists/JUnitParams執行此操作:
假設您有一個Person對象,必須指定所有參數,然后可以使用JUnitParams這樣進行測試:
@Test(expected = IllegalArgumentException.class)
@Parameters(
{", bloggs, joe.bloggs@ig.com",
"joe, , joe.bloggs@ig.com,",
"joe, bloggs, ,",
)
public void allParametersAreMandatory(String firstName, String lastName, String emailAddress)
{
new Person(firstName, lastName, emailAddress);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.