I like the idea of using an In-Memory Database such as SQLite when testing instead of creating Mocks for my Repositories. This way I can also test the code of my Repositories without any performance iss开发者_开发技巧ues.
What are the pros and cons of this strategy?
If I'm using an ORM, I generally tend to use a sqlite in memory database for testing my apps since I don't have the overhead of setting up the mocks and expected results. There's a speed boost over using a dummy database but I don't expect it to be faster than using a mock. If I were using an SQL adaptor, I would probably use a mock since otherwise, I'd probably have to rewrite the calls.
I would say those two strategies are two different things. As you said yourself, with in-memory db you can test your repositories as well, however, you have to test your repositories first to achieve separation of concerns. When you are designing your system, maybe according to the MVC, you want your Controllers before Models/Repositories, because firstly you have to decide what do you want to do and afterthat decide which entities will collaborativelly achieve that goal. So maybe creating controllers and mocking repositories first is a better way, afterwards you can test your repositories using the in-memory database if it is really easy to setup.
My strategy is when testing my business code, I mock out my repository. When testing my repository, I mock out my data access layer. I use, as much as possible, auto-generated code for my data access layer (LINQ-to-SQL) so there isn't much to test there. What there is (validation stuff, specialized property handling), can usually be tested directly, without mocks. If absolutely necessary (or easier) I will sometimes fake the data layer with a custom, in-memory store built on Lists -- see my blog at http://farm-fresh-code.blogspot.com where I've written about this.
Using an in-memory gives you an advantage which mocking wouldn't. Using in-memory database, you can easily change code implementation without changing anything in the tests. For example, if using an ORM, you can move form using insert
method to bulkInsert
method without having to mock the newly added bulkInsert
method.
精彩评论