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 -
https://gist.github.com/deodeveloper/405bfbaf8ad94a37304dbfe8949f5757



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() :
                defaultValue(fieldType));
      }
    }
  }

  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:
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>




No comments:

Post a Comment