Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing BeanUtils / test should fail when a new property is created

I'm using BeanUtils to map some DTO class to Domain classes (and vice/versa). (using BeanUtils copy properties)

I want to test my code. How do I write test that will fail if someone writes creates an extra property in either the DTO or Domain class.

My attempt which I'm still working on is to traverse BeanUtils.getPropertyDescriptors(class) and find the corresponding getter methods THEN for each class (DTO and Domain) test for equality.

Any thoughts?

Due to project dependency constraints I would rather not use something like Dozer. I am using spring 3's beanutils.

like image 382
user48545 Avatar asked Nov 13 '22 15:11

user48545


1 Answers

If you're concerned just with testing for extra properties, your test method could look like this:

void assertSameProperties(Class class1, Class class2) {
    Set<String> properties = new HashSet<String>();
    for (PropertyDescriptor prop : BeanUtils.getPropertyDescriptors(class1)) {
        properties.add(prop.getName());
    }
    for (PropertyDescriptor prop : BeanUtils.getPropertyDescriptors(class2)) {
        if (!properties.remove(prop.getName()) {
            fail("Class " + class2.getName() + " has extra property " + prop.getName());
        }
    }
    if (!properties.isEmpty()) {
        fail("Class " + class1.getName() + " has extra properties");
    }

}

If you are concerned with testing the mapping itself, then your approach with calling getters for each property that exists in both classes and checking their results for equality should work. Remember about 'class' property, though, its value will certainly be different for objects of different classes.

like image 82
socha23 Avatar answered Nov 16 '22 15:11

socha23