Friday, June 5, 2015

Mocking SQL Server database layer in Unit tests with C# and Moq

In this post I will describe how to mock database layer in Unit Tests with C# and Moq.

Why it is needed? Well, good question.
Tests that verify that DB communications works are no longer just unit tests, they are integration tests. But quite often integration tests require more complex setup, they take longer time to execute, there should be some initialization & deployment process done to make them reliable.  Also it is hard to test all of the corner cases like connectivity issues, invalid schemas or backward compatibility.

In that case old good Unit tests can help. It requires some ground work to create few mocks but after that it is relatively easy to write unit tests.
I will use Moq framework and Unity. Unity is not mandatory, I just find it helpful in my case.
Lets say I have a class to test that communicates with database. It opens connection and queries some data and returns list of some mode objects:
 

And this is the driver application: To be able to write unit tests we need to define few support classes as some of the classes can't be mocked with Moq framework (they are internal classes, etc. Sample class that can't be mocked: SqlParameterCollection) MockDataReader (most of the methods are not implemented. I implemented only necessary methods): Mock parameter collection: Connection factory helper: In case you need to override Unity setup you can use that class: And then finally the Unit test:

No comments:

Post a Comment