From e5fd50016f47e7fd3d12a60ec292b83f64b24272 Mon Sep 17 00:00:00 2001 From: tdurieux Date: Tue, 7 Mar 2017 13:27:56 +0100 Subject: [PATCH] buggy files form Mockito #21 --- .../instance/ConstructorInstantiator.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 projects/Mockito/21/org/mockito/internal/creation/instance/ConstructorInstantiator.java 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); + } + } +}