Jay
Jay

Reputation: 21

How do I go about this unit test?

I don't know how to write a unit test for some code I have. I understand what's going on in the code, but I'm not sure how to go about writing a unit test for it.

I have tried, but I am stumped at the moment. The code simply prints out an array of first names and strips out the special characters. I want to test the first line of the code and test if the special characters are stripped.

firstNameParts = new ArrayList<String>(Arrays.asList(first.split("( |-)")));
System.out.println("Length of First Name Parts: " + firstNameParts.size());
for (int i = 0; i < firstNameParts.size(); i++) {
    System.out.println("First Name Part " + i + ":" + firstNameParts.get(i));
    // strip out special chars
    firstNameParts.set(i,firstNameParts.get(i).replaceAll("[^A-Za-z]+", ""));
    System.out.println("Stripped First Name Part " + i + ":" + firstNameParts.get(i));
}

Upvotes: 1

Views: 57

Answers (1)

Bohemian
Bohemian

Reputation: 425448

To test, and to better organise your code, you should separate the "action" code from the "rendering" code. This makes each unit of action easily testable:

static List<String> extractNameParts(String name) {
    return new ArrayList<String>(Arrays.asList(first.split("[ -]")));
}

static String removeSpecialChars(String str) {
    return  str.replaceAll("[^A-Za-z]+", "");
}

These are obviously easy to test, because they only do one thing.

Note how the name of the method is basically a variant of the comment in your code. As a rule of thumb, instead of writing a comment, create a method instead. Doing this formally names the code, makes it reusable and testable. Your code will look neater and more readable too.

Here's what it might look like:

firstNameParts = extractNameParts(first);
System.out.println("Length of First Name Parts: " + firstNameParts.size());

for (int i = 0; i < firstNameParts.size(); i++) {
    String namePart = firstNameParts.get(i);
    System.out.println("First Name Part " + i + ":" + );
    firstNameParts.set(i, removeSpecialChars(namePart);
    System.out.println("Stripped First Name Part " + i + ":" + namePart);
}

As for testing the output, you could have your code print to a specified PrintStream (of which System.out is one) instead of assuming the code prints to the console. You could then have your test code pass a PrintStream to the code then examine its contents.

Upvotes: 1

Related Questions