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

io.github.simplefixture.valuegenerator.EnumValueGenerator Maven / Gradle / Ivy

There is a newer version: 1.0.0-rc
Show newest version
package io.github.simplefixture.valuegenerator;

import io.github.simplefixture.utils.ClassUtils;
import io.github.simplefixture.config.FixtureConfig;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Random;

public final class EnumValueGenerator extends AbstractValueGenerator implements ValueGenerator{

    private Type type;
    private FixtureConfig config;
    private Field field;

    public EnumValueGenerator(Type type){
        this.type = type;
    }

    @Override
    public EnumValueGenerator config(FixtureConfig config) {
        this.config = config;
        return this;
    }

    @Override
    public EnumValueGenerator field(Field field) {
        this.field = field;
        return this;
    }

    @Override
    public Enum create() {
        try {
            return config.getTheme().getValue(0, field, getValue());
        }catch (ClassCastException e) {
            throw new ClassCastException("'" + field.getName() + "' Property's type is not match. check your property value.");
        }
    }

    private Enum getValue(){
        Class aClass = ClassUtils.castToClass(type);

        String fieldName = field.getName();
        Map values = config.getValues();

        if (values.containsKey(fieldName)) {
            if(values==null){
                return null;
            }
            return (Enum) values.get(fieldName);
        } else {
            return (Enum) aClass.getEnumConstants()[new Random().nextInt(aClass.getEnumConstants().length)];
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy