Super simple Java bean tester

Efficient bean testing with Java 8 and jOOR
October 1, 2015 by Michael

This is not about bean testing is effective, right or whatever. Just assume you want your Java beans tested, for example to achieve full code coverage.

There are some solutions out there and I used to use the BeanLikeTester but the library and i have different opinions about the hashCode/equals contract so i decided to run my own in a new project.

This one conveniently tests all setters and getters:

import java.util.Locale;
import java.util.function.BiConsumer;
import org.joor.Reflect;
// If you have jOOQ on the path instead of jOOR
// import org.jooq.tools.reflect.Reflect; 
import org.junit.Assert;
 
public class BeanTester implements BiConsumer<String, Object> {
 
    private final Reflect r;
 
    public BeanTester(Class<?> clazz) {
	this.r = Reflect.on(clazz).create();
    }
 
    @Override
    public void accept(String p, Object v) {
	final String property = p.substring(0, 1).toUpperCase(Locale.ENGLISH) + p.substring(1);
	final String verbSet = "set";
	final String verbGet = v instanceof Boolean ? "is" : "get";
	try {
	    Assert.assertEquals(v, r.call(verbSet + property, v).call(verbGet + property).get());
	} catch(Exception e) {
	    e.printStackTrace();
	    Assert.fail(e.getMessage());
	}
    }
}

You’ll need jOOR to make this work. jOOR is a small but highly functional reflection API.

This is how i use it at the moment:

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
 
public class BeanTesterDemo {
    static class Demo {
	private String attr1;
 
	private boolean attr2;
 
	private LocalDate attr3;
 
	public String getAttr1() {
	    return attr1;
	}
 
	public void setAttr1(String attr1) {
	    this.attr1 = attr1;
	}
 
	public boolean isAttr2() {
	    return attr2;
	}
 
	public void setAttr2(boolean attr2) {
	    this.attr2 = attr2;
	}
 
	public LocalDate getAttr3() {
	    return attr3;
	}
 
	public void setAttr3(LocalDate attr3) {
	    this.attr3 = attr3;
	}	
    }
 
    @Test
    public void beanShouldWorkAsExpected() {
	final Map<String, Object> values = new HashMap<>();
	values.put("attr1", "foobar");
	values.put("attr2", true);
	values.put("attr3", LocalDate.now());
 
	values.forEach(new BeanTester(Demo.class));
    }
}

No comments yet

Post a Comment

Your email is never published nor shared. Required fields are marked *