Loading...

Counter-Strings: Self-Describing Test Data

One of the methods from Rapid Software Testing with James Bach, is to use self describing test data like counter strings. The string for the count 10 will give you exactly the character position. This is useful for boundary testing and and testing large input strings. Counter strings are helpful testing sizes of UI text and database fields.

James Bach offers a tool written in Perl. This post illustrates the implementation in Java.

The counter string for 10 is

*3*5*7*10*

The algorithm implemented in Java:

public class TestStringUtil {
    private static final String POS_MARKER = "*";
    public static String createCounterString(final int length) {
        StringBuilder sb = new StringBuilder();
        int lastPos = Math.abs(length);
        // descending fill counter string
        while (lastPos > 0) {
            // e.g. 35 = 35*
            String token = String.valueOf(lastPos) + POS_MARKER;
            // 3<35
            if (token.length() <= lastPos) {
                // insert at beginning
                sb.insert(0, token);
            } else {
                // 2<1, truncate to last remaining position
                sb.insert(0, token.substring(lastPos, token.length()));
            }
            // compute next counter string position, e.g. 35 - 3 = 32
            lastPos -= token.length();
        }
        return sb.toString();
    }
}

See also Parameterized Tests with JUnit for the respective tests of this algorithm.