Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Database Mocks in ASP.NET MVC using Data from Existing Database

I have an existing ASP.NET MVC application with some sample data in the SQL Server database, which is working fine..

Assuming I have all of the necessary repositories and IOC in place, is there a tool that will extract the data from a group of tables, and "freeze-dry" it into a mock object (perhaps using an XML file to store the data), so that I can detach the database and use the mock data for my unit tests?

like image 888
Robert Harvey Avatar asked Jun 22 '10 16:06

Robert Harvey


2 Answers

Depending on what exactly you are trying to test there might be different approaches.

If you want to test the data access logic then this is no longer unit test but integration test. For this kind of tests it is a good idea to be able to easily replace the real database with some lighter maybe even in-memory database like SQLite which will be reconstructed before running each test. If you are using an ORM this task is easy. All you need to do is to generate SQL scripts (INSERT INTO...) from your existing database, modify and adapt the dialect to SQLite (if necessary), read and inject into a SQLite file and finally all that's left is to instruct your data access layer to use SQLite dialect and connection string for the unit test.

Now if you are not using an ORM and your data access logic is tied to MSSQL things get uglier you will need a live database in order to perform those integration tests. In this case I would suggest you duplicate your real database which you would use for the tests by modifying only the connection string. Once again you will need to properly setup and teardown (preferably in a transaction) this test database in order to put it into a known state for the tests.

If you want to test code that depends on those repositories (such as your controllers for example) you don't need to even bother about mocking the data as your controllers depend on abstract repositories and not the real implementations (aren't they), so you could easily mock the methods of the repository in order to test the logic in the controllers.

like image 152
Darin Dimitrov Avatar answered Sep 23 '22 14:09

Darin Dimitrov


This is actually a well known "test smell":

http://xunitpatterns.com/Obscure%20Test.html#General

From: 2098937: Proper way to Mock repository objects for unit tests using Moq and Unity

like image 40
John Farrell Avatar answered Sep 21 '22 14:09

John Farrell