0

I am very new to Java, and testing a small piece of Java code:

I have a java program which work like a calculator and writes input/output to console in a tabular format-

Inputs:
+-+-----+
| |1    |
+-+-----+
|A|1 + 1|
+-+-----+
Results:
+-+-------+
| |1      |
+-+-------+
|A|2.00000|
+-+-------+

Can anyone help on how to write JUNIT ASSERT statement to validate that program is printed in the right format with right values?

I am doing black-box testing and does not have understanding on the code/class/method written within the code.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
shaan
  • 1
  • 1
  • 1
    Just for the record: please read https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question ... the main reason I answered is: because it is possible to give you some help without doing all your homework. – GhostCat May 21 '17 at 19:32
  • I have already achieved, the snippet of code you have given.. I am looking for opinion..if the exact format printed in the output console can be tested. The code do ensure that calculation is happening correctly, but it does not ascertain if the string appear as 1st, 2nd , 3rd etc line of output. assertTrue(outContent.toString().contains("|A|2.00000|")); – shaan May 21 '17 at 21:48

1 Answers1

1

You can write tests that really test that your "class under test" prints expected output using System.out (see here for details).

But the better approach: your class under test should have a method that returns the expected content as String.

And your unit tests call these methods, and compare Strings against expected values. You see, in the real world, printing to System.out doesn't matter or doesn't happen. So spending a lot of time to test that aspect of your production code is not something that you gain too much from.

In other words, reasonable tests would more like:

@Test
public void testInputs() {
  Whatever underTest = new Whatever();
  underTest.add(1);
  asserThat(underTest.getResult(); is("|A|2.00000|"));
}

or something alike.

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • The class API has to indeed be testable. First rule of a testable code. – davidxxx May 21 '17 at 19:31
  • I have written as below, but it does not test that output is written in exact format which i have pasted in my question- assertTrue(outContent.toString().contains("|A|2.00000|")); – shaan May 21 '17 at 19:33
  • 1
    @davidxxx Which is probably not too easy in this case. But that is why one should do tdd, to come up with testable APIs right from the beginning .... – GhostCat May 21 '17 at 19:34
  • I agree totally for TDD. Like you, I am a big fan :) – davidxxx May 21 '17 at 19:47