diff --git a/projects/Mockito/21/org/mockito/internal/creation/instance/ConstructorInstantiator.java b/projects/Mockito/21/org/mockito/internal/creation/instance/ConstructorInstantiator.java new file mode 100644 index 0000000..0cc8226 --- /dev/null +++ b/projects/Mockito/21/org/mockito/internal/creation/instance/ConstructorInstantiator.java @@ -0,0 +1,45 @@ +package org.mockito.internal.creation.instance; + +import java.lang.reflect.Constructor; + +public class ConstructorInstantiator implements Instantiator { + + private final Object outerClassInstance; + + public ConstructorInstantiator(Object outerClassInstance) { + this.outerClassInstance = outerClassInstance; + } + + public T newInstance(Class cls) { + if (outerClassInstance == null) { + return noArgConstructor(cls); + } + return withOuterClass(cls); + } + + private T withOuterClass(Class cls) { + try { + //this is kind of overengineered because we don't need to support more params + //however, I know we will be needing it :) + Constructor c = cls.getDeclaredConstructor(outerClassInstance.getClass()); + return c.newInstance(outerClassInstance); + } catch (Exception e) { + throw paramsException(cls, e); + } + } + + private static InstantationException paramsException(Class cls, Exception e) { + return new InstantationException("Unable to create mock instance of '" + + cls.getSimpleName() + "'.\nPlease ensure that the outer instance has correct type and that the target class has parameter-less constructor.", e); + } + + + private static T noArgConstructor(Class cls) { + try { + return cls.newInstance(); + } catch (Exception e) { + throw new InstantationException("Unable to create mock instance of '" + + cls.getSimpleName() + "'.\nPlease ensure it has parameter-less constructor.", e); + } + } +}