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

org.unitils.objectvalidation.rules.ToStringMustContainsEveryFieldRule Maven / Gradle / Ivy

There is a newer version: 1.1.9
Show newest version
package org.unitils.objectvalidation.rules;

import static java.util.Arrays.asList;
import static org.junit.Assert.assertTrue;

import java.lang.reflect.Field;
import java.util.List;

import org.unitils.objectvalidation.ObjectCreator;
import org.unitils.objectvalidation.Rule;


/**
 * Rule to check that the toString method returns a string with every field named in it.
 * 
 * @author Matthieu Mestrez
 * @since Oct 24, 2013
 */
public class ToStringMustContainsEveryFieldRule implements Rule {

    private static final List FIELDS_NAME_TO_IGNORE = asList("serialVersionUID", "$jacocoData");
    
    private ObjectCreator objectCreator;

    public ToStringMustContainsEveryFieldRule(ObjectCreator objectCreator) {
        this.objectCreator = objectCreator;
    }
    
    @Override
    public void validate(Class classToValidate) {
        Field[] fields = classToValidate.getDeclaredFields();
        
        Object objectToTest = objectCreator.createRandomObject(classToValidate);
        
        for (Field field : fields) {
            if (!FIELDS_NAME_TO_IGNORE.contains(field.getName())) {
                assertTrue("The field " + field.getName() + " is not in the toString :\n" + objectToTest.toString(),
                            objectToTest.toString().contains(field.getName()));
            }
        }
    }
    
    

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy