Comparing output in a JUnit test

Output matching is a built in test type in ClassCube. The catch is that you may not always want to compare that the output matches exactly. Or, maybe you want to do your own comparisons.

To do this you’ll need to create your own JUnit test and use the unit testing grade type. Fortunately, it’s pretty easy to deal with output from stdOut and stdErr.

The Code

Let’s start by looking at an example JUnit test file. There’s only a shell test method called, creatively test. Take a look and then we’ll talk about the code.

Instance Variables

Notice that we’re creating two instance variables outContent and errContent. Both are ByteArrayOutputStream. We’re going to use these to store the output from stdOut and stdErr respectively.


We’re also going to use a set of 4 methods. captureOut turns on capture of stdOut and getOut returns the value and turns the capture off. captureErr and getErr do the same except for stdErr.

The idea is that you call the captureOut method whenever you want to start capturing the output. Then you do call the tested methods that are producing output. After you’ve called the method you’re testing you store the results of getOut into a String. Compare that string with what you’re expecting.

Same applies to the captureErr and getErr pair of methods.

Do you need this?

If you’re using ClassCube and just want to do an exact output comparison you don’t need to go through this. There’s an output matching grading type built in. You’d just select output matching and paste in the expected output. No reason to build your own test files.

That said, this code is similar to what we use behind the scenes when you select output matching as the grading type.

Why ClassCube?

Are you spending too much time grading your students' source code?

ClassCube is an online tool for Computer Science teachers that allows you to create lab assignments for your students. They'll submit their code online and ClassCube will automatically grade it for you.

More Info …

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>