@Test
 public void testGenericMethodWithoutGenericExceptionTypes() throws Exception {
   DynamicType.Unloaded<?> unloaded =
       new ByteBuddy()
           .redefine(GenericMethod.class)
           .method(named(BAR))
           .intercept(FixedValue.nullValue())
           .make();
   Class<?> type =
       unloaded
           .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
           .getLoaded();
   MethodDescription createdMethod =
       new MethodDescription.ForLoadedMethod(type.getDeclaredMethod(BAR, Object.class));
   MethodDescription originalMethod =
       new MethodDescription.ForLoadedMethod(
           GenericMethod.class.getDeclaredMethod(BAR, Object.class));
   assertThat(createdMethod.getTypeVariables(), is(originalMethod.getTypeVariables()));
   assertThat(createdMethod.getReturnType(), is(originalMethod.getReturnType()));
   assertThat(
       createdMethod.getParameters().getOnly().getType(),
       is(originalMethod.getParameters().getOnly().getType()));
   assertThat(
       createdMethod.getExceptionTypes().getOnly(),
       is(originalMethod.getExceptionTypes().getOnly()));
 }
 public void apply()
     throws IllegalAccessException, InvocationTargetException, InstantiationException {
   if (type.isEnum()) {
     for (T instance : type.getEnumConstants()) {
       assertThat(
           instance.toString(),
           is(
               type.getCanonicalName().substring(type.getPackage().getName().length() + 1)
                   + "."
                   + ((Enum<?>) instance).name()));
     }
     return;
   }
   for (Constructor<?> constructor : type.getDeclaredConstructors()) {
     if (constructor.isSynthetic() && skipSynthetic) {
       continue;
     }
     constructor.setAccessible(true);
     Class<?>[] parameterTypes = constructor.getParameterTypes();
     Object[] actualArguments = new Object[parameterTypes.length];
     Object[] otherArguments = new Object[parameterTypes.length];
     int index = 0;
     for (Class<?> parameterType : parameterTypes) {
       putInstance(parameterType, actualArguments, otherArguments, index++);
     }
     int testIndex = 0;
     @SuppressWarnings("unchecked")
     T instance = (T) constructor.newInstance(actualArguments);
     assertThat(instance, is(instance));
     assertThat(instance, not(is((Object) null)));
     assertThat(instance, not(is(new Object())));
     Object similarInstance = constructor.newInstance(actualArguments);
     assertThat(instance.hashCode(), is(similarInstance.hashCode()));
     assertThat(instance, is(similarInstance));
     if (skipToString) {
       assertThat(instance.toString(), notNullValue());
     } else if (optionalToStringRegex == null) {
       checkString(instance);
     } else {
       assertThat(instance.toString(), new RegexMatcher(optionalToStringRegex));
     }
     for (Object otherArgument : otherArguments) {
       Object[] compareArguments = new Object[actualArguments.length];
       int argumentIndex = 0;
       for (Object actualArgument : actualArguments) {
         if (argumentIndex == testIndex) {
           compareArguments[argumentIndex] = otherArgument;
         } else {
           compareArguments[argumentIndex] = actualArgument;
         }
         argumentIndex++;
       }
       Object unlikeInstance = constructor.newInstance(compareArguments);
       assertThat(instance.hashCode(), not(is(unlikeInstance)));
       assertThat(instance, not(is(unlikeInstance)));
       testIndex++;
     }
   }
 }
    /*
     * (non-Javadoc)
     * @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock)
     */
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {

      Class<?> returnType = invocation.getMethod().getReturnType();
      return returnType.equals(Boolean.class) || returnType.equals(boolean.class)
          ? true
          : DEFAULT.answer(invocation);
    }
 @Test
 public void testSourceName() throws Exception {
   for (Class<?> type : standardTypes) {
     if (type.isArray()) {
       assertThat(describe(type).getActualName(), is(type.getComponentType().getName() + "[]"));
     } else {
       assertThat(describe(type).getActualName(), is(type.getName()));
     }
   }
 }
 @Test
 public void testEnclosingType() throws Exception {
   for (Class<?> type : standardTypes) {
     assertThat(
         describe(type).getEnclosingType(),
         type.getEnclosingClass() == null
             ? nullValue(TypeDescription.class)
             : is((TypeDescription) new TypeDescription.ForLoadedType(type.getEnclosingClass())));
   }
 }
 @Test
 public void testSetClassName() throws Exception {
   Intent intent = new Intent();
   Class<? extends IntentTest> thisClass = getClass();
   intent.setClassName("package.name", thisClass.getName());
   assertSame(thisClass.getName(), intent.getComponent().getClassName());
   assertEquals("package.name", intent.getComponent().getPackageName());
   ShadowIntent si = shadowOf(intent);
   assertSame(si.getIntentClass(), thisClass);
 }
 @Test
 public void testGenericField() throws Exception {
   DynamicType.Unloaded<?> unloaded = new ByteBuddy().redefine(GenericField.class).make();
   Class<?> type =
       unloaded
           .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
           .getLoaded();
   FieldDescription createdField = new FieldDescription.ForLoadedField(type.getDeclaredField(FOO));
   FieldDescription originalField =
       new FieldDescription.ForLoadedField(GenericField.class.getDeclaredField(FOO));
   assertThat(createdField.getType(), is(originalField.getType()));
 }
  /** simple case. */
  @Test
  public void simple() {
    Class<? extends DirectFileOutputDescription> aClass =
        generate(new Description("Testing", name(MockData.class)));
    assertThat(DirectFileOutputDescription.class.isAssignableFrom(aClass), is(true));
    assertThat(Modifier.isAbstract(aClass.getModifiers()), is(true));

    assertThat(aClass, hasGetter("getModelType"));
    assertThat(aClass, not(hasGetter("getBasePath")));
    assertThat(aClass, not(hasGetter("getResourcePattern")));
    assertThat(aClass, not(hasGetter("getFormat")));
  }
 public static Class<?> malform(Class<?> type) throws Exception {
   ClassReader classReader = new ClassReader(type.getName());
   ClassWriter classWriter = new ClassWriter(classReader, 0);
   classReader.accept(new SignatureMalformer(classWriter), 0);
   ClassLoader classLoader =
       new ByteArrayClassLoader(
           null,
           Collections.singletonMap(type.getName(), classWriter.toByteArray()),
           null,
           ByteArrayClassLoader.PersistenceHandler.MANIFEST,
           PackageDefinitionStrategy.NoOp.INSTANCE);
   return classLoader.loadClass(type.getName());
 }
 @SuppressWarnings("unchecked")
 private void apply(Object mock) {
   for (Refinement refinement : refinements) {
     ParameterizedType generic =
         (ParameterizedType) refinement.getClass().getGenericInterfaces()[0];
     Class<?> restrained =
         generic.getActualTypeArguments()[0] instanceof ParameterizedType
             ? (Class<?>) ((ParameterizedType) generic.getActualTypeArguments()[0]).getRawType()
             : (Class<?>) generic.getActualTypeArguments()[0];
     if (restrained.isInstance(mock)) {
       refinement.apply(mock);
     }
   }
 }
 private void assertAnnotations(Class<?> type) {
   assertThat(
       describe(type).getDeclaredAnnotations(),
       hasItems(
           new AnnotationList.ForLoadedAnnotation(type.getDeclaredAnnotations())
               .toArray(new AnnotationDescription[type.getDeclaredAnnotations().length])));
   assertThat(
       describe(type).getDeclaredAnnotations().size(), is(type.getDeclaredAnnotations().length));
   assertThat(
       describe(type).getInheritedAnnotations(),
       hasItems(
           new AnnotationList.ForLoadedAnnotation(type.getAnnotations())
               .toArray(new AnnotationDescription[type.getAnnotations().length])));
   assertThat(describe(type).getInheritedAnnotations().size(), is(type.getAnnotations().length));
 }
  @SuppressWarnings("unchecked")
  @Test
  public void test() throws Exception {
    assertThat(compile("input/Example.java"), is(true));

    URLClassLoader loader = new URLClassLoader(new URL[] {res("input/")});
    Class<?> exampleClass = loader.loadClass("Example");
    Object exampleObj = exampleClass.newInstance();
    assertThat(
        (List<String>)
            exampleClass
                .getMethod("transform", List.class)
                .invoke(exampleObj, Arrays.<Integer>asList(1, 2, 3)),
        is(Arrays.<String>asList("2", "4", "6")));
  }
 @Test
 @ToolsJarRule.Enforce
 public void testAgentSelfInitializationAuxiliaryTypes() throws Exception {
   assertThat(ByteBuddyAgent.installOnOpenJDK(), instanceOf(Instrumentation.class));
   ClassFileTransformer classFileTransformer =
       new AgentBuilder.Default()
           .rebase(isAnnotatedWith(ShouldRebase.class), ElementMatchers.is(classLoader))
           .transform(new QuxTransformer())
           .installOnByteBuddyAgent();
   try {
     Class<?> type = classLoader.loadClass(Qux.class.getName());
     assertThat(type.getDeclaredMethod(FOO).invoke(type.newInstance()), is((Object) (FOO + BAR)));
   } finally {
     ByteBuddyAgent.getInstrumentation().removeTransformer(classFileTransformer);
   }
 }
 private void checkString(T instance) {
   assertThat(
       instance.toString(),
       CoreMatchers.startsWith(
           type.getCanonicalName().substring(type.getPackage().getName().length() + 1) + "{"));
   assertThat(instance.toString(), endsWith("}"));
   Class<?> currentType = type;
   do {
     for (Field field : type.getDeclaredFields()) {
       if (!field.isSynthetic()
           && !Modifier.isStatic(field.getModifiers())
           && !ignoredFields.contains(field.getName())) {
         assertThat(instance.toString(), containsString(field.getName()));
       }
     }
   } while ((currentType = currentType.getSuperclass()) != Object.class);
 }
 @Test
 public void testEnclosingMethod() throws Exception {
   for (Class<?> type : standardTypes) {
     Matcher<MethodDescription> matcher;
     if (type.getEnclosingMethod() != null) {
       matcher =
           CoreMatchers.<MethodDescription>is(
               new MethodDescription.ForLoadedMethod(type.getEnclosingMethod()));
     } else if (type.getEnclosingConstructor() != null) {
       matcher =
           CoreMatchers.<MethodDescription>is(
               new MethodDescription.ForLoadedConstructor(type.getEnclosingConstructor()));
     } else {
       matcher = nullValue(MethodDescription.class);
     }
     assertThat(describe(type).getEnclosingMethod(), matcher);
   }
 }
 @Test
 @ToolsJarRule.Enforce
 public void testAgentWithoutSelfInitializationWithNativeMethodPrefix() throws Exception {
   assertThat(ByteBuddyAgent.installOnOpenJDK(), instanceOf(Instrumentation.class));
   ClassFileTransformer classFileTransformer =
       new AgentBuilder.Default()
           .disableSelfInitialization()
           .withNativeMethodPrefix(QUX)
           .rebase(isAnnotatedWith(ShouldRebase.class), ElementMatchers.is(classLoader))
           .transform(new FooTransformer())
           .installOnByteBuddyAgent();
   try {
     Class<?> type = classLoader.loadClass(Baz.class.getName());
     assertThat(type.getDeclaredMethod(FOO).invoke(type.newInstance()), is((Object) BAR));
     assertThat(type.getDeclaredMethod(QUX + FOO), notNullValue(Method.class));
   } finally {
     ByteBuddyAgent.getInstrumentation().removeTransformer(classFileTransformer);
   }
 }
  /**
   * generate concrete class.
   *
   * @throws Exception if failed
   */
  @Test
  public void concrete() throws Exception {
    Description description = new Description("Testing", name(MockData.class));
    description.setBasePath("base-path");
    description.setResourcePattern("*");
    description.setFormatClassName(name(MockDataFormat.class));

    Class<? extends DirectFileOutputDescription> aClass = generate(description);
    assertThat(DirectFileOutputDescription.class.isAssignableFrom(aClass), is(true));
    assertThat(Modifier.isAbstract(aClass.getModifiers()), is(false));

    DirectFileOutputDescription object = aClass.newInstance();
    assertThat(object.getModelType(), is((Object) MockData.class));
    assertThat(object.getBasePath(), is("base-path"));
    assertThat(object.getResourcePattern(), is("*"));
    assertThat(object.getOrder(), is(Arrays.<String>asList()));
    assertThat(object.getDeletePatterns(), is(Arrays.<String>asList()));
    assertThat(object.getFormat(), is((Object) MockDataFormat.class));
  }
 @Test
 public void testIsPackageDescription() throws Exception {
   assertThat(
       describe(
               Class.forName(
                   Sample.class.getPackage().getName()
                       + "."
                       + PackageDescription.PACKAGE_CLASS_NAME))
           .isPackageType(),
       is(true));
   assertThat(describe(Object.class).isPackageType(), is(false));
 }
 private Object replace(Class<?> type, ApplicableGenerator generator, boolean alternative) {
   for (Creator<?> creator : creators) {
     ParameterizedType generic =
         (ParameterizedType) creator.getClass().getGenericInterfaces()[0];
     Class<?> restrained =
         generic.getActualTypeArguments()[0] instanceof ParameterizedType
             ? (Class<?>) ((ParameterizedType) generic.getActualTypeArguments()[0]).getRawType()
             : (Class<?>) generic.getActualTypeArguments()[0];
     if (type.isAssignableFrom(restrained)) {
       return creator.create();
     }
   }
   return generator.generate(type, alternative);
 }
 private Object generate(Class<?> type, boolean alternative) {
   for (Generator<?> generator : generators) {
     ParameterizedType generic =
         (ParameterizedType) generator.getClass().getGenericInterfaces()[0];
     Class<?> restrained =
         generic.getActualTypeArguments()[0] instanceof ParameterizedType
             ? (Class<?>) ((ParameterizedType) generic.getActualTypeArguments()[0]).getRawType()
             : (Class<?>) generic.getActualTypeArguments()[0];
     if (type.isAssignableFrom(restrained)) {
       type = generator.generate();
     }
   }
   return type == String.class ? alternative ? OTHER_STRING : DEFAULT_STRING : mock(type);
 }
 private void putInstance(
     Class<?> parameterType, Object actualArguments, Object otherArguments, int index) {
   Object actualArgument, otherArgument;
   if (parameterType == boolean.class) {
     actualArgument = DEFAULT_BOOLEAN;
     otherArgument = OTHER_BOOLEAN;
   } else if (parameterType == byte.class) {
     actualArgument = DEFAULT_BYTE;
     otherArgument = OTHER_BYTE;
   } else if (parameterType == char.class) {
     actualArgument = DEFAULT_CHAR;
     otherArgument = OTHER_CHAR;
   } else if (parameterType == short.class) {
     actualArgument = DEFAULT_SHORT;
     otherArgument = OTHER_SHORT;
   } else if (parameterType == int.class) {
     actualArgument = DEFAULT_INT;
     otherArgument = OTHER_INT;
   } else if (parameterType == long.class) {
     actualArgument = DEFAULT_LONG;
     otherArgument = OTHER_LONG;
   } else if (parameterType == float.class) {
     actualArgument = DEFAULT_FLOAT;
     otherArgument = OTHER_FLOAT;
   } else if (parameterType == double.class) {
     actualArgument = DEFAULT_DOUBLE;
     otherArgument = OTHER_DOUBLE;
   } else if (parameterType.isEnum()) {
     Object[] enumConstants = parameterType.getEnumConstants();
     if (enumConstants.length == 1) {
       throw new IllegalArgumentException("Enum with only one constant: " + parameterType);
     }
     actualArgument = enumConstants[0];
     otherArgument = enumConstants[1];
   } else if (parameterType.isArray()) {
     actualArgument = Array.newInstance(parameterType.getComponentType(), 1);
     otherArgument = Array.newInstance(parameterType.getComponentType(), 1);
     putInstance(parameterType.getComponentType(), actualArgument, otherArgument, 0);
   } else {
     actualArgument = creator.replace(parameterType, generator, false);
     refinement.apply(actualArgument);
     otherArgument = creator.replace(parameterType, generator, true);
     refinement.apply(otherArgument);
   }
   Array.set(actualArguments, index, actualArgument);
   Array.set(otherArguments, index, otherArgument);
 }
 public void applyBasic()
     throws IllegalAccessException, InvocationTargetException, InstantiationException {
   for (Constructor<?> constructor : type.getDeclaredConstructors()) {
     if (constructor.isSynthetic() && skipSynthetic) {
       continue;
     }
     constructor.setAccessible(true);
     Class<?>[] parameterTypes = constructor.getParameterTypes();
     Object[] actualArguments = new Object[parameterTypes.length];
     Object[] otherArguments = new Object[parameterTypes.length];
     int index = 0;
     for (Class<?> parameterType : parameterTypes) {
       putInstance(parameterType, actualArguments, otherArguments, index++);
     }
     @SuppressWarnings("unchecked")
     T instance = (T) constructor.newInstance(actualArguments);
     checkString(instance);
     assertThat(instance, is(instance));
     assertThat(instance, not(is((Object) null)));
     assertThat(instance, not(is(new Object())));
     assertThat(instance, not(is(constructor.newInstance(otherArguments))));
   }
 }
 @Test
 public void testToString() throws Exception {
   for (Class<?> type : TYPES) {
     assertThat(describe(type).toString(), is(type.toString()));
   }
 }
 @Test
 public void testCanonicalName() throws Exception {
   for (Class<?> type : standardTypes) {
     assertThat(describe(type).getCanonicalName(), is(type.getCanonicalName()));
   }
 }
 @Test
 public void testIsLocalClass() throws Exception {
   for (Class<?> type : standardTypes) {
     assertThat(describe(type).isLocalClass(), is(type.isLocalClass()));
   }
 }
 @Test
 public void testModifiers() throws Exception {
   for (Class<?> type : standardTypes) {
     assertThat(describe(type).getModifiers(), is(type.getModifiers()));
   }
 }
 @Test
 public void testName() throws Exception {
   for (Class<?> type : TYPES) {
     assertThat(describe(type).getName(), is(type.getName()));
   }
 }