Pregunta

I have a class which does the following

class PersonDumper {

    // attributes

    public PersonDumper(PrintStream output, Set<Person> persons) {
        // do stuff
    }

    public dump() {
        for(Person p : persons) {
            output.print(p);
            output.print(",");
        }
    }
}

The thing is that I want to test that the formatting I am giving to the Person objects (in the example I want to print the toString() method), and so on is right.

Then I would like to test the output with something like this:

public class ListPrintStream extends PrintStream {
    private List<List<String>> output;
    // every time I call to print I do output.add(string)
}

Then, I can get that List> and read it in order to test if I am outputting what I want.

But I have problems with the constructor used for PrintStream. Because, in my case, I don't want any argument for the constructor.

Do you think that I am using a good approach? Shall I use the OutputStream class instead of PrintStream? Any hint?

Edit to ask:

Does anyone know a PrintStream that is used for testing?

¿Fue útil?

Solución

You could pass a dummy output stream to the superclass constructor, such as the NullOutputStream from Apache commons-io, which is an OutputStream implementation that silently discards all data written to it.

Alternatively, you could consider declaring your PersonDumper to take an instance of Appendable instead. PrintStream implements Appendable so this won't change your code in the normal case, but for testing you could pass in a StringBuilder or similar instead.

class PersonDumper {

    // attributes

    public PersonDumper(Appendable output, Set<Person> persons) {
        // do stuff
    }

    public dump() {
        for(Person p : persons) {
            // String.valueOf rather than .toString to be null-safe
            output.append(String.valueOf(p));
            output.append(",");
        }
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top