Search code examples
testingagilelegacy-codefit-framework

Testing a legacy code


I'm following a course in agile practices and I have a homework. What they taught me, is that before changing the code (refactoring or adding functionality) I should add some test, in order to gain confidence and be sure that I will not change the behavior while refactoring. This is clear and makes sense, but what if the code is not testable without doing some refactoring first?

Simple example:

public class Summation
{
    private int addend1;
    private int addend2;

    public Summation(int addend1, int addend2)
    {
        this.addend1 = addend1;
        this.addend2 = addend2;
    }

    public int doSum()
    {
        System.out.println(addend1 + addend2);
    }

    // Getters/setters
}

I would like to run an acceptance/integration test using FIT, and check that the following table is verified:

 ----------------------------
| addend1 | addend2 | result |
 ----------------------------
| 1       | 1       | 2      |
 ----------------------------
| 1       | -1      | 0      |
 ----------------------------
| -1      | 1       | 0      |
 ----------------------------
| -1      | -1      | -2     |
 ----------------------------

But, because the function doSum() prints the sum to the standard output stream, it's difficult to write a test for it (I prefer to avoid to intercept the standard output). It would make more sense to slightly refactor the code in order to have a method that returns the sum. But because I'm technically "not allowed" to change the code before writing any test, this is not recommended.

Can you give me any hints? How would you proceed?

Thank you!


Solution

  • Sounds similar to this question.

    Whether or not you're allowed to change the code, you're forced to intercept standard output stream. In any case, it's a part of the behaviour.