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>




2 comments:


  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

    ReplyDelete
  2. Great Article android based projects

    Java Training in Chennai Project Center in Chennai Java Training in Chennai projects for cse The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai

    ReplyDelete