Should we unit test console outputs?

匆匆过客 提交于 2019-12-01 19:19:10

Is it correct to try to unit test System.out.print()'s?

This highly depends on what you are trying to test. I don't think it is necessary to test System.out.print() itself, I hope Sun/Oracle has done this enough. But if your application outputs important information to the console and this is your only way to validate the output, than yes, you need to test it. If you can test your code by testing the corresponding classes, then you probably don't need to test the output stream itself.

Look at databases, for example: I don't test the JDBC driver it self, but I do test all code/functionality that is part of loading/saveing data from and to the database.

The red line only means the code line was never executed. This can be okay or it could mean that your tests don't touch a part of your code that they should. Getting test coverage high is important, but aiming for 100% might not always be necessary (think Pareto principle)

As for your Null Pointer Exception

Your call to System.setOut(null); set the System.out to null and eCobertura probably tries to write something to Standard Out, which is null now. You might need to save the orignial Out Stream in your @Before Method and restore it in our @After method to allow the code that follows to use StdOut

Is eCobertura incompatible with this type of test?

If eCobertura is not compatible with this type of test, why does it show the line red?

why is eCobertura giving me this error?

It could be that the communication between eclipse and eCobertura happens via Standard Out, but I am not sure. If this is the case, than if you redirect Standard Out not only your output but also the output from Cobertura gets redirected and the GUI does not see anymore what gets executed and what not, thus coloring it red

Is there something wrong in my test?

It might be necessary to ensure StdOut is correctly restored.

I am using jUnit 4.11 do you think this has something to do with it?

No, I don't think so

If it's correct to use System.out.println's in your code, then it's correct to (unit/integration) test them.

There is a useful System test utility called System Rules for testing this kind of code.

http://stefanbirkner.github.com/system-rules/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!