1. Introduction
1.1. Benefits of Project
This project provides a collection of test tools for unit testing.
1.2. Getting Started
Include dependencies to build.gradle:
build.gradle
apply plugin: 'java'
dependencies {
testCompile "org.softcake.lemon:lemon-core:1.1.0"
}
2. Test Tools
2.1. Private Constructor Tester
You need to test even private constructors of classes that must not be instantiated.
For example you have such class with private constructor:
Demo class example
/**
* Demo class
*/
public final class Demo {
private Demo() {
throw new IllegalStateException("No instances!");
}
public static void checkNotNull(final Object obj) {
if (obj == null) {
throw new IllegalArgumentException("Parameter must not be null!");
}
}
}
We need reflection to access the private Constructor.
Test with reflection
@Test
public void constructorMustBePrivateAndThrowException_Old() {
try {
Constructor<?>[] constructors = Demo.class.getDeclaredConstructors();
Constructor<?> constructor = constructors[0];
constructor.setAccessible(true);
constructor.newInstance();
fail("constructor must throw exception");
} catch (final InvocationTargetException expected) {
IllegalStateException cause = (IllegalStateException) expected.getCause();
assertEquals("No instances!", cause.getMessage());
} catch (InstantiationException | IllegalAccessException e) {
fail("constructor must throw IllegalStateException");
}
}
Solution to avoid this boilerplate:
PrivateConstructorTester
@Test
public void constructorMustBePrivateAndThrowException_New() {
PrivateConstructorTester
.forClass(Demo.class)
.expectedExceptionType(IllegalStateException.class, "No instances!")
.check();
}
To check nested classes, you must provide an Instance of enclosing class. See this example:
Nested class example
/**
* enclosing class
*/
public final class EnclosingClass {
private EnclosingClass() {
}
//some methods
/**
* non static nested class
*/
private final class NestedClass {
private NestedClass() {
throw new IllegalStateException("No instances!");
}
//some methods
}
}
And the solution:
PrivateConstructorTester and TestUtils
@Test
public void constructorMustBePrivateAndThrowException() {
String nestedClassName = "NestedClass";
Object enclosingInstance = TestUtil.getEnclosingInstance(EnclosingClass.class,
new Object[]{},
new Class[]{});
Class<?> nestedClass = TestUtil.forNestedName(nestedClassName, enclosingInstance);
PrivateConstructorTester
.forClass(nestedClass, enclosingInstance)
.expectedExceptionType(IllegalStateException.class, "No instances!")
.check();
}
It is not possible to test nested classes, if constructor of the enclosing class throws an exception on instantiating! |