0

I am sure this is a silly question but I simply do not know - suppose I have a method that is expected to do nothing for certain inputs. Like, value < 10, print chars, otherwise do nothing. Basically, the unit test would pass for the actual method or for one with just an empty body. How do I write a failing test for such an instance?

John V
  • 4,855
  • 15
  • 39
  • 63
  • Are you actually printing from the method? Why not return from the method and have something else (e.g., `main`) do the actual printing? – Mureinik May 19 '18 at 09:30
  • @Mureinik Well this was jus an example that crossed my mind. But I hope the point is clear – John V May 19 '18 at 10:27
  • Possible duplicate of [How to test void method with Junit testing tools?](https://stackoverflow.com/questions/1244541/how-to-test-void-method-with-junit-testing-tools) – GhostCat May 19 '18 at 16:45
  • In your example you will test that standard output prints given number if number greater then 10. For "do nothing" you will test that standard output is empty after method executed. – Fabio May 19 '18 at 21:43

1 Answers1

0

Your unit tests assertions should be based on unit observable effects — return value or (unfortunately) side effects. Sometimes you do want to test behavior instead of result with help of mocks, but this makes tests fragile.

If you have a value returned everything is simple, you just check that value satisfies some known postconditions.

In case of side effects, you are forced to setup proper test environment (some global state for example), and then check how it was changed. For your concrete example you may redirect output and verify later that something was written to it on values less than 10 and nothing was written otherwise.

So generally you still want to check that method did nothing, because it's a separate execution flow.

Uladzislaŭ
  • 1,680
  • 10
  • 13