All Downloads are FREE. Search and download functionalities are using the official Maven repository.

autofixture.generators.objects.ConcreteObjectGenerator Maven / Gradle / Ivy

The newest version!
package autofixture.generators.objects;

import autofixture.exceptions.ObjectCreationException;
import autofixture.generators.objects.implementationdetails.Debug;
import autofixture.interfaces.*;
import com.google.common.base.Optional;
import org.objenesis.ObjenesisStd;

import java.util.List;

public class ConcreteObjectGenerator implements InstanceGenerator {

  private boolean omittingAutoProperties = false;

  private final ObjenesisStd objenesis = new ObjenesisStd(true);

  @Override
  public  boolean appliesTo(final InstanceType typeToken) {
    return true;
  }

  @Override
  public  T next(final InstanceType type, final FixtureContract fixture) {
    final T instance = createInstanceOf(type, fixture);
    try {
      if (!omittingAutoProperties) {
        makeBestEffortAttemptToInvokeAllSettersOn(instance, type, fixture);
        makeBestEffortAttemptToSetAllPublicFields(instance, type, fixture);
      }

    } catch (final IllegalAccessException e) {
      throw new ObjectCreationException(type, e);
    }
    return instance;
  }

  @Override
  public  T nextEmpty(final InstanceType instanceType, final FixtureContract fixture) {
    return objenesis.newInstance((Class)instanceType.getRawType());
  }

  private  void makeBestEffortAttemptToSetAllPublicFields(final T instance,
                                                             final InstanceType type, final FixtureContract fixture) throws IllegalAccessException {
    final List> publicFields = type.getAllPublicSettableFieldsOf(instance);
    for (final InstanceField publicField : publicFields) {
      publicField.setValueUsing(fixture);
    }
  }

  private  T createInstanceOf(final InstanceType type, final FixtureContract fixture) {
    final Call currentConstructor = type.findSuitableConstructorWithLeastParameters();
    final T instance = currentConstructor.invokeWithArgumentsCreatedUsing(fixture);
    return instance;
  }

  private  void makeBestEffortAttemptToInvokeAllSettersOn(final T instance,
                                                             final InstanceType type, final FixtureContract fixture) {
    final List> setters = type.getAllSetters();
    for (final Call setter : setters) {
      makeBestEffortAttemptToInvoke(setter, instance, fixture);
    }
  }

  private  void makeBestEffortAttemptToInvoke(final Call setter,
                                                 final T instance, final FixtureContract fixture) {
    try {
      setter.invokeWithArgumentsCreatedUsing(fixture, Optional.of(instance));
    } catch (final Exception t) {
      Debug.print(t);
    }
  }

  @Override
  public void setOmittingAutoProperties(final boolean isOn) {
    this.omittingAutoProperties = isOn;

  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy