Question

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!

Was it helpful?

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.

OTHER TIPS

You could write a test.cpp file to call Summation.Summation(x,y) with various values for x and y in your table and verify/record the results. Make sure the results are what you expect. Next, you may now edit the Summation class and run your tests again (from test.cpp) to ensure the values are the same as they were initially.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top