Unit Test case Unit test is a piece of code that instantiates a small portion of our application and verifies its behavior independently from other parts Essentially, it tests a method of a class May or may not be functional More about designing components than finding bugs and regression. 2
BOUNDARIES Only the code of the method is tested Except entities (up to you), everything else needs to be mocked Must not persist anything and avoid interacting with File System, network or databases Do not test the framework related aspects 3
Characteristics Every test case should be independent of each other Should not be dependent on ordering of tests Avoid test cases with side effects Must run very fast O therwise they will not be used every time Avoid using sleep or wait like methods Can be run multiple times without any intervention 4
Naming conventions Follow a standard naming convention testGetEmployee testGetEmployeeByString shouldReturnEmployeeObjectWithIdEqualsTo2012 givenAnEmployeeWithNameMichaelExists_WhenGetEmployeeByNameIsCalledWithStringMichael_ThenEmployeeObjectWithNameMichaelIsReturned 5
Three Steps Prepare T ry not to reuse creation logic of entities across project Act Assert Use a single assert, it forges Single Responsibility Principle Use equals method instead of individual fields of object 6
Coverage A Method is either covered or not 80% coverage does not give any indication Better to have 3 methods covered 100% in a class of 5 methods than whole class covered 90% and none of the methods fully covered Understand the difference between line and condition coverage Meaningful coverage rather than coverage 7
Coverage etc. Refactor test cases like you refactor your code If required, use descriptive messages in asserts, avoid comments assertEquals ("Calculated tax must be $30,000", expected, required); 8