Further, in this post, I will write the best practices you must consider before writing your test cases.Table of Contents: Unit testing is not about finding bugs Tips for writing great unit tests Test only one code unit at a time Don’t make unnecessary assertions Make each test independent to all the others Mock out all external services and state Don’t unit-test configuration settings Name your unit tests clearly and consistently Write tests for methods that have the fewest dependencies first, and work your way up All methods, regardless of visibility, should have appropriate unit tests Aim for each unit test method to perform exactly one assertion Create unit tests that target exceptions Use the most appropriate assertion methods.Put assertion parameters in the proper order Ensure that test code is separated from production code Do not print anything out in unit tests Do not use static members in a test class Do not write your own catch blocks that exist only to fail a test Do not rely on indirect testing Integrate Testcases with build script Do not skip unit tests Capture results using the XML formatter Summary In programming, “Unit testing is a method by which individual units of source code are tested to determine if they are fit for use.” Now, this unit of source code can very on different scenarios.
Before writing this post, I am assuming that you know the basics of junit.
If you do not have the basic knowledge, first read this link.
Also, this is important because you would not love to debug the test cases which are actually failing due to bugs in some external system.(By the way, sometimes your architecture might mean your code touches static variables during unit tests.
Avoid this if you can, but if you can’t, at least make sure each test resets the relevant statics to a known state before it runs.) By definition, your configuration settings aren’t part of any unit of code (that’s why you extracted the setting out in some properties file).
To have some employee in database, your create employee test cases must pass before moving forward.
In this way, if there is some error in employee creation logic, it will be detected much earlier. You need to look for most critical portions of your code and you should test them without worrying if they are even private.You must name your testcases on what they actually do and test.Testcase naming convention which uses class names and method names for testcases name, is never a good idea.These methods can have certain critical algorithm called from one or two classes, but they play important part.You would like to be sure that they work as intended.Try to use @Before and @After methods to setup per-requisites if any for all your test cases.