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

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

package autofixture.generators.objects;

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

import java.util.List;

public class ConcreteObjectGenerator implements InstanceGenerator {

  private boolean omittingAutoProperties = false;

  @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;
  }

  private  void makeBestEffortAttemptToSetAllPublicFields(final T instance,
                                                             final InstanceType type, final FixtureContract fixture) throws IllegalAccessException {
    final List> publicFields = type.getAllPublicFieldsOf(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.debugPrint(t);
    }
  }

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

  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy