Thursday, December 8, 2011

Unit test tips

Automated unit tests provide a safety net to enhance application so that we wont be afraid to make a change without introducing defects and it also makes an application more maintainable.
Unit test names must be robust; They should be named after the functionality that they are testing. A recommended way to name unit tests is to use the Noun+should+verb pattern.

A body of a test method should be arranged using the AAA pattern (arrange, act, assert).
-          Arrange: This section contains code that sets up the variables that will be used by the unit test.
-          Act : This section execercises the unit under testing and capture the results.
-          Assert: This section verifies the results of the unit test against expectations.

Avoid tests that do too much. Verify only a single concept to make it easier to pinpoint the cause of failures.

A good point is to have only a single assert statement in a test method. If you have multiple asserts, make sure that they are verifying the same concept.

Unit testing with a real database brings a number of challenges:
1.       It significantly slows down the execution time of unit tests.The longer it takes to run the tests, the less likely you will run them frequently. Ideally you would want unit tests to run in seconds- something you do naturally as compiling the project.
2.       It complicates the setup and cleanup logic within the tests. You want each unit test to be isolated and independent of the others with no side effects or dependencies. When working against a real database, you have to be also mindful of state and reset the values between the tests.
To overcome this challenge, it is recommended to use the dependency injection design pattern.

Dependency Injection
Dependencies, like repository classes are no longer implicitly created within the classes that use them. This will allow us to test specific scenarios without requiring a connection to the database.