Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock DataReader to unit test DAL

Tags:

c#

I have a method in my data access layer that performs mapping. The method accepts a DataReader, and maps the data to the proper domain object properties. Is there a good way to somehow mock the DataReader so I can perform unit tests on the mapping methods without hitting against a physical database?

like image 707
dretzlaff17 Avatar asked Aug 26 '10 18:08

dretzlaff17


1 Answers

Lucky for you, DataReader implements the IDataReader interface.

Instead of relying on a DataReader in your code, use IDataReader. Then, in your tests you can substitute your own implementation that returns dummy data, or use a mocking framework like Rhino.Mocks or similar to create the stubs and assign return values.

Depending on how you're "getting" the DataReader in your code, you may need to do a little refactoring. What you want is to have external dependencies like this "injected" in the constructor (preferred) or through a property, so that consumers of the class can substitute any implementation of IDataReader. (This substitution is also why you declare your parameters/properties as abstractions rather than concrete types.) This is known as Dependency Injection, a form of Inversion of Control.

like image 129
Jay Avatar answered Nov 01 '22 23:11

Jay