GNGiseldo Neo and Alana NeoBooks
Introduction to Programming in Java16 / 25

Testing and Refactoring

Changing structure without losing behavior

15.1 Learning Objectives

By the end of this chapter, you should be able to:

  • turn requirements into test cases;
  • distinguish unit tests from flow tests;
  • apply the red–green–refactor cycle;
  • recognize duplication and excessive responsibilities;
  • refactor while preserving observable results.

15.2 Tests as Specification

Short cycle of test-driven development.

Figure 15.1. Short cycle of test-driven development.

A test contains setup, action, and assertion. Before adopting an external library, you can practice the idea with a simple verifier:

import java.util.Locale;

public class Chapter15Testing {
    static String normalize(String input) {
        if (input == null) {
            return "";
        }
        return input.strip().toLowerCase(Locale.ROOT);
    }

    static void verify(String description, Object expected, Object actual) {
        if (!expected.equals(actual)) {
            throw new AssertionError(
                    description + " | expected=" + expected + ", actual=" + actual);
        }
    }

    public static void main(String[] args) {
        verify("removes spaces", "help", normalize("  help "));
        verify("ignores uppercase", "tip", normalize("TIP"));
        verify("handles null", "", normalize(null));

        System.out.println("3 tests passed.");
    }
}

This didactic helper does not replace JUnit in professional projects, but it makes the structure of a test explicit without adding external dependencies to the book.

15.3 Edge Cases

For each method, cover:

  • the typical case;
  • empty input;
  • minimum and maximum boundaries;
  • unknown values;
  • expected errors;
  • state before and after the operation.

A test should fail for one clear reason. Avoid bundling too many rules into a single check.

15.4 Refactoring

Comic: the test that found a bug.

Figure 15.2. Comic: the test that found a bug.

Refactoring means changing internal structure without altering external behavior. A safe cycle is:

  1. write or run tests;
  2. make a small change;
  3. run the tests again;
  4. record any important decision.

Signs that refactoring is needed:

  • a long method;
  • a long chain of if or switch statements;
  • a repeated rule;
  • a class with unrelated responsibilities;
  • an exposed internal collection;
  • direct dependence on the console inside business rules.

15.5 Chatbot Regression Script

In addition to method tests, run a complete flow:

ScenarioInputExpected result
helphelpall commands are listed
normalizationTIPcommand is found
emptyblank lineguidance message, nothing recorded in history
historyhi, historyprevious interaction is displayed
persistenceend sessionfile contains the recorded lines
duplicationregister two identical commandsclear exception

15.6 Project Evolution: Version 15

Write tests for normalization, command registration, and history before replacing conditionals with polymorphic objects. If the same tests keep passing, the refactoring preserved the contract.

The complete example is in examples/src/Chapter15Testing.java.

15.7 Verifiable Practice

  1. Make a test fail on purpose and read the message.
  2. Test an expected exception using try/catch.
  3. Extract a duplicated rule and confirm the tests stay green.
  4. Write a manual test script with exact inputs and outputs for the final project.

Next professional step

Once you master this structure, migrate these cases to JUnit in a Maven or Gradle project. The library changes; the arrange–act–assert logic remains the same.