Database free NUnit tests
How can I test my code (TDD) for standard CRUD operations without having a database. 开发者_StackOverflowIs it possible to achieve such level of isolation so that my code is database independent.
Thanks a lot guys.
Yep. You write an Interface with all the call to the database you would want.
Then you create two classes that implement the interface.
One has real access to your database.
The other, just pretends, it's a mock implementation.
Use fakes, like Rhino Mocks, to mock the data access. That way when your tests run they will interact with the fake instead of going all the way down to the database.
Q1:
How can I test my code (TDD) for standard CRUD operations without having a database.
I see that the post is tagged with nunit, so I assume a .net context. Given that, I've personally utilized SQLite as an in-memory database successfully in a project for a few months time now (together with NHibernate and common DDD-patterns).
Q2:
Is it possible to achieve such level of isolation so that my code is database independent.
I don't think that it's possible to write fully database independent code, but NHibernate takes me 95% of the way there (but that number depends heavily on your specific context).
Furthermore, with good data-access patterns, e.g. «Repository» and «Unit of Work», the rest of the code base can be made 100% database agnostic. The same goes for other data sources, e.g. CSV and XML files.
You can test the business layer (and some of the presentation layer) using Mock objects.
Use Mocks/Fakes so that instead of calling the database from the DAL a fake class will be called instead and return a predefined value.
In order to test the DAL you will need actual database. You can use a unit testing framework to run simple CRUD on the database. Create a simple test database as well as a restore point and use the unit testing framework's setup & teardown to make sure your database is in the expected state.
精彩评论