Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何测试构造函数将抛出非法状态异常?_Java_Unit Testing_Testing_Junit_Constructor - Fatal编程技术网

Java 如何测试构造函数将抛出非法状态异常?

Java 如何测试构造函数将抛出非法状态异常?,java,unit-testing,testing,junit,constructor,Java,Unit Testing,Testing,Junit,Constructor,我有一个带有私有构造函数的实用程序类,它抛出一个非法的状态异常,我想测试它是否能做到这一点 我尝试了一个实现构造函数的测试,但是由于构造函数是私有的,所以不能在类之外访问它。那么,测试构造函数是否毫无意义 从班上 private UtilityClass(){ throw new IllegalStateException("Utility Class"); } 从测试班 private UtilityClass = utilityClass; @Test(e

我有一个带有私有构造函数的实用程序类,它抛出一个非法的状态异常,我想测试它是否能做到这一点


我尝试了一个实现构造函数的测试,但是由于构造函数是私有的,所以不能在类之外访问它。那么,测试构造函数是否毫无意义

从班上

 private UtilityClass(){
        throw new IllegalStateException("Utility Class");
    }
从测试班

private UtilityClass = utilityClass;
    @Test(expected = IllegalStateException.class)
    public void constructorTest(){
        utilityClass = new UtilityClass();
    }

您可以通过定义公共构造函数,然后编写适当的测试代码来测试构造函数是否引发异常。如果你有一个私有构造函数(或私有方法),你就不能直接测试它。

你有从外部获取实例的静态方法吗?“那么测试构造函数是没有意义的吗?”Yupyou将它设为私有,这样就没有人可以访问它,而且你可能在其中一个方法或构造函数中使用它。所以只要测试一下这个方法,我同意。你应该直接测试一个方法——如果它们可以被公共访问的话。您的构造函数是私有的,因此如果它被公共方法使用,那么您应该测试这些方法以检测异常。更改代码以使用接口而不是类。然后没有更多的构造函数,没有什么要测试的。