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

com.github.nylle.javafixture.specimen.AbstractSpecimen Maven / Gradle / Ivy

Go to download

JavaFixture is the attempt to bring Mark Seemann's AutoFixture for .NET to the Java world. Its purpose is to generate full object graphs for use in test suites with a fluent API for customising the test objects during generation.

There is a newer version: 2.11.0
Show newest version
package com.github.nylle.javafixture.specimen;

import com.github.nylle.javafixture.Context;
import com.github.nylle.javafixture.CustomizationContext;
import com.github.nylle.javafixture.ISpecimen;
import com.github.nylle.javafixture.InstanceFactory;
import com.github.nylle.javafixture.SpecimenException;
import com.github.nylle.javafixture.SpecimenFactory;
import com.github.nylle.javafixture.SpecimenType;

import java.lang.annotation.Annotation;

public class AbstractSpecimen implements ISpecimen {

    private final SpecimenType type;
    private final Context context;
    private final InstanceFactory instanceFactory;

    public AbstractSpecimen(final SpecimenType type, final Context context, final SpecimenFactory specimenFactory) {

        if (type == null) {
            throw new IllegalArgumentException("type: null");
        }

        if (context == null) {
            throw new IllegalArgumentException("context: null");
        }

        if (specimenFactory == null) {
            throw new IllegalArgumentException("specimenFactory: null");
        }

        if (!type.isAbstract() || type.isMap() || type.isCollection()) {
            throw new IllegalArgumentException("type: " + type.getName());
        }

        this.type = type;
        this.context = context;
        this.instanceFactory = new InstanceFactory(specimenFactory);
    }

    @Override
    public T create(final CustomizationContext customizationContext, Annotation[] annotations) {
        if (context.isCached(type)) {
            return context.cached(type);
        }

        try {
            return (T) context.cached(type, instanceFactory.proxy(type));
        } catch(SpecimenException ignored) {
            return context.cached(type, instanceFactory.manufacture(type, customizationContext));
        }
    }
}





© 2015 - 2025 Weber Informatics LLC | Privacy Policy