private void check ( Class clazz ) { final Constructor < ? > [ ] constructors = clazz . getDeclaredConstructors ( ) ; if ( constructors . length > 1 ) { throw new AssertionError ( clazz + " has more than one constructor" ) ; } final Constructor < ? > constructor = constructors [ 0 ] ; constructor . setAccessible ( true ) ; if ( ! Modifier . isPrivate ( constructor . getModifiers ( ) ) ) { throw new AssertionError ( "Constructor of " + clazz + " must be private" ) ; } final Class < ? > [ ] parameterTypes = constructor . getParameterTypes ( ) ; if ( parameterTypes . length > 0 ) { if ( expectedParameters == null ) { throw new AssertionError ( clazz + " has non-default constructor with some parameters" ) ; } else { if ( ! Arrays . equals ( parameterTypes , expectedParameters ) ) { throw new AssertionError ( "Expected constructor with parameters " + getReadableClassesOutput ( expectedParameters ) + " but found constructor with parameters " + getReadableClassesOutput ( parameterTypes ) ) ; } else { return ; } } } try { constructor . newInstance ( ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( "Can not instantiate instance of " + clazz , e ) ; } catch ( IllegalAccessException e ) { // Fixed by setAccessible(true) throw new RuntimeException ( e ) ; } catch ( InvocationTargetException e ) { final Throwable cause = e . getCause ( ) ; // It's okay case if we expect some exception from this constructor if ( expectedTypeOfException != null || expectedExceptionMessage != null ) { if ( expectedTypeOfException != null && ! expectedTypeOfException . equals ( cause . getClass ( ) ) ) { throw new IllegalStateException ( "For " + clazz + " expected exception of type = " + expectedTypeOfException + ", but was exception of type = " + e . getCause ( ) . getClass ( ) ) ; } if ( expectedExceptionMessage != null && ! expectedExceptionMessage . equals ( cause . getMessage ( ) ) ) { throw new IllegalStateException ( "For " + clazz + " expected exception message = '" + expectedExceptionMessage + "', but was = '" + cause . getMessage ( ) + "'" , e . getCause ( ) ) ; } // Everything is okay } else { throw new IllegalStateException ( "For " + clazz + " no exception was expected" , e ) ; } } catch ( IllegalArgumentException e ) { throw new RuntimeException ( "Looks like constructor of " + clazz + " is not default" , e ) ; } }
Runs the check which will assert that particular class has one private constructor which throws or not throws exception .