Ryan is a Java developer working in software engineering research. His research mainly focuses on source code analysis and development tools. Ryan has posted 24 posts at DZone. You can read more from them at their website. View Full User Profile

Why Do We Need to do Software Testing?

04.30.2013
| 5521 views |
  • submit to reddit

Why do we need to test our program?

When people talk about the importance of software testing, common examples they give frequently are military software, aircraft, etc. That is not concrete enough to understand why we need to test our software.

Here I provide an example from daily programming work. You don’t need to work for a military project to understand why we need software testing.

The example provided here is capitalize(String str) method from org.apache.commons.lang3.StringUtils which is from Apache Commons Lang library.

The following method capitalizes a given string. Suppose you write this method for your project. How do you know if this method is reliable and always return what it should return? We need to test! That is, given all different kinds of input, we see if it returns expected results. The returned results can either be good or bad, but they should be expected.

public static String capitalize(String str) {
    int strLen;
    if (str == null || (strLen = str.length()) == 0) {
        return str;
    }
    return new StringBuilder(strLen)
        .append(Character.toTitleCase(str.charAt(0)))
        .append(str.substring(1))
        .toString();
}

The testing code for this method is below. I have removed the code for testing other methods.

The testing code tests different kinds of inputs, such as null, an empty string, a single-char-string, and results of another method. In this way, we can assert this method is reliable.

@Test
public void testCaseFunctions() {
    assertEquals(null, StringUtils.capitalize(null));
 
    assertEquals("capitalize(empty-string) failed", "", StringUtils.capitalize("") );
 
    assertEquals("capitalize(single-char-string) failed", "X", StringUtils.capitalize("x") );
         
    // reflection type of tests: Sentences.
    assertEquals("capitalize(uncapitalize(String)) failed",
                     SENTENCE_CAP, StringUtils.capitalize(StringUtils.uncapitalize(SENTENCE_CAP)) );
 
    // reflection type of tests: One word.
    assertEquals("capitalize(uncapitalize(String)) failed",
                     FOO_CAP, StringUtils.capitalize(StringUtils.uncapitalize(FOO_CAP)) );
 
}

The assertEquals method is from JUnit framework which is the defacto standard of unit testing.

(source )



 

Published at DZone with permission of its author, Ryan Wang. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)