Friday, May 18, 2018

Testing A Java Bean For Code Coverage in SonarQube

Here is a generic way of testing a java bean to provide 100% code coverage on sonarqube.

Remember, if beans are trivial, please use this approach, otherwise write proper test cases.

Complete Source code is here -

Sample Source code -

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.PropertyUtils;

public class BeanTester {

public static <T>  void testBean(Class<T>... beanClasses) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
    for (Class<T> beanClass : beanClasses) {
      T bean = beanClass.newInstance();
      Field[] declaredFields = beanClass.getDeclaredFields();
      for (Field f : declaredFields) {
        PropertyUtils.getProperty(bean, f.getName());
        Class<?> fieldType = f.getType();
        PropertyUtils.setProperty(bean, f.getName(),
            !fieldType.isPrimitive() ? fieldType.newInstance() :

  public static <T> T defaultValue(Class<T> type) {
    if (type == boolean.class) {
      return (T) Boolean.FALSE;
    } else if (type == char.class) {
      return (T) Character.valueOf('\0');
    } else if (type == byte.class) {
      return (T) Byte.valueOf((byte) 0);
    } else if (type == short.class) {
      return (T) Short.valueOf((short) 0);
    } else if (type == int.class) {
      return (T) Integer.valueOf(0);
    } else if (type == long.class) {
      return (T) Long.valueOf(0L);
    } else if (type == float.class) {
      return (T) Float.valueOf(0f);
    } else if (type == double.class) {
      return (T) Double.valueOf(0d);
    } else {
      return null;


usage example - testBean(Person.class)
dependencies used:


  1. This is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article.

    Website Design and Development Company

    Website Design Company

    Website Development Company

    Wordpress Customization comapany

    SEO Company

    digital marketing company

  2. I really like this post and would like to share a content to you free of cost. I have written an original and 100% unique article on the topic How To Build A Web Application With Node JS. The article is of length 1000 words if you agree to publish it here I can send it to you right now. Please reply me on I shall be looking forward to your reply soon. ...Thanks and regards