繁体   English   中英

具有不同参数的Java测试构造函数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM