我有一个带构造函数的类,它得到如下输入:
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 :(得分: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
答案 1 :(得分:1)
将Project1 = new Project(....
和Project2 = new Project(.....
保留在各自的try catch块中。通过第一个块抛出的异常不会阻止以后的代码部分运行。
答案 2 :(得分: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(...);
}
}
如果您想测试所有可能的参数组合,那么数据提供者或理论可能会有用。
答案 3 :(得分:0)
您可以使用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);
}