This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I have to write JUnittest cases for my class CheckVul (code below) but it's my first time using JUnit and am stuck on how to make test cases for these methods since they all are void, and write to a file. The checkDatabase method takes in a 'profile name' and a 'year' provided by the user, to compare that profile with the database of that year and check for vulnerabilities. I have a basic understanding of how to write test cases for simple methods that return something, etc. but not for this. Any suggestions? :S I was thinking making a test case for the checkDatabase method would be simple, but not sure how to go about it.
If I were the one being asked to test this, I would first have a serious talk with the developer about the design.
First, it's not unit testable since it expects input from a file. A unit test should not cross system boundaries, that is, it should not access the file system, a database, a web service, etc. For this class, you can only write integration tests, which are expected to cross system boundaries.
Second, the design violates the Open-Closed Principle. What happens in 2013? In 2014? In 2015? etc. Seems like you'd need to change this code every year. That's not a good design.
One other nitpick (my pet peeve): why skimp on keystrokes and make the class name less readable? What's wrong with naming the class VulnerabilityChecker or something that is easy to read without having to do a mental expansion? Write code with the reader in mind. Don't skimp on keystrokes this way. BTW, a class name should generally be a noun or noun phrase. CheckVul, assuming "Vul" is a lazy short form of "Vulnerability", is a verb phrase and is more suitable as a method name.
Another thing, why are the checkVul**() methods public? Shouldn't these be private instead? It looks like the checkDatabase() method is meant to be called and then it will call the appropriate checkVul**() method. Since the checkVul** methods are public, there's nothing that prevents them from being called with the wrong parameter values. If they are meant to be public, then why have the checkDatabase() method at all?