Tag Archives: testing

Covering Utility Classes

Coverage is one of my personal metric I try get close to 100% as part of my programming style to quickly make sure I at least went through all the possible code paths.

I have three criteria for a well defined utility class:

  • It has only one private constructor
  • It has no non-static methods
  • It is final

This is based on my answer about testing against private constructors and I use it to test my utility classes to push up my coverage metric.

import static org.junit.Assert.*;
import java.lang.reflect.*;

public static void assertUtilityClassWellDefined(Class<?> clazz)
        throws NoSuchMethodException, InvocationTargetException,
        InstantiationException, IllegalAccessException {
    assertTrue("class must be final",
            Modifier.isFinal(clazz.getModifiers()));
    assertEquals("There must be only one constructor", 1,
            clazz.getDeclaredConstructors().length);
    final Constructor<?> constructor = clazz.getDeclaredConstructor();
    if (constructor.isAccessible() || 
                !Modifier.isPrivate(constructor.getModifiers()) {
        fail("constructor is not private");
    }
    constructor.setAccessible(true);
    constructor.newInstance();
    constructor.setAccessible(false);
    for (final Method method : clazz.getMethods()) {
        if (!Modifier.isStatic(method.getModifiers())
                && method.getDeclaringClass().equals(clazz)) {
            fail("there exists a non-static method:" + method);
        }
    }
}

I have placed the full code and examples in https://github.com/trajano/commons-testing/.

Generating a random SIN

The Canadian Social Insurance Number is something that would validate against the Luhn algorithm. Since SINs may be used as input data for some applications, I have translated the code that generates a number that passes the Luhn Algorithm in Wikipedia to something that can be put into into Selenium’s user-extensions.js.

Selenium.prototype.getRandomSIN = function() {
    var length = 9;
    var digits = new Array();
    for(var i = 0; i < length - 1; ++i) {         digits[i] = Math.floor(Math.random() * 9)     }     var sum = 0;     var alt = true;     for(var i = length - 2; i >= 0; --i) {
        if (alt) {
            var temp = digits[i];
            temp *= 2;
            if (temp > 9) {
                temp -= 9;
            }
            sum += temp;
        } else {
            sum += digits[i];
        }
        alt = !alt;
    }

    var modulo = sum % 10;
    if(modulo > 0) {
        digits[length-1] = 10 - modulo;
    }
    return digits.join("");
};