Unit testing using Mock objects and dependency injectionPresentation Transcript
Unit testing using Mock objects and dependency injection Rajasekhar Reddy, Talentica Software
Automated dependency injection
Unit testing is a method by which individual units of source code are tested to determine if they are fit for use.
A unit smallest amount of testable code. Often a single method/function
Features of good unit tests
They should be fast
They should never use
An app server (or server of any kind)
File/Network I/O or file system
Benefits of unit testing
Unit testing allows the programmer to refactor code at a later date, and make sure the module still works correctly (e.g., in regression testing). Whenever a change causes a fault, it can be quickly identified and fixed.
Unit testing provides a sort of living documentation of the system. Developers looking to learn what functionality is provided by a unit and how to use it can look at the unit tests to gain a basic understanding of the unit's API.
Mock objects are simulated objects that mimic the behavior of real objects
If an object has any of the following characteristics, it may be useful to use a mock object in its place:
supplies non-deterministic results (e.g. the current time or the current temperature);
has states that are difficult to create or reproduce (e.g. a network error);
is slow (e.g. a complete database, which would have to be initialized before the test);
Dependency injection means giving an object its instance variables.
Simple: Nothing to learn, no dependencies.
No reflection magic: In IDE it is easy to find out who calls the constructors.
Even developers who do not understand DI can follow and contribute to projects.
Using manual caller has to know about all the dependencies, using automated DI it will inject all the dependencies so caller do not have to know about dependencies
Why developers hate unit tests
Have to write more code
Wants to jump to cool new feature quickly
requires them to face their own potentially imperfect code