Reputation: 6884
What's a good approach for writing unit tests for the following GetMyObjectsFiltered(...)
method in a EF4 repository:
public static class MyRepository
{
public static List<MyObject> GetMyObjectsFiltered(string searchFilter)
{
var myQueryableObjects = GetMyObjects(searchFilter);
if (false == string.IsNullOrWhiteSpace(searchFilter))
{
myQueryableObjects = myQueryableObjects.Where(o => o.MyProperty.Contains(searchFilter));
}
return myQueryableObjects.ToList();
}
private static IQueryable<MyObject> GetMyObjects(string searchFilter)
{
using (MyDB_ModelContainer model = new MyDB_ModelContainer())
{
return model.MyTable.AsQueryable();
}
}
}
Can I inject the MyDB_ModelContainer
and still utilise the using
statement?
Upvotes: 0
Views: 216
Reputation: 6884
In the end I have refactored out the static class, and made a very thin layer over EF that returns only IQueryable types. Implemented via an interface this class can then be easily stubbed using Moles. A full description is provided in the following blog post:
Upvotes: 0
Reputation: 15579
well what an irony you are asking about unit testing and you have a static method right there..
rread this: Static methods are death to testability
Also related to your question.. unit testing repository code is really not needed if you dont have business logic there cos you will basically end up testing the ORM as part of your unit tests which is not necessary as the ORM writers would have already taken care of it.
If you refactor the static method to another interface implementation then you could mock an implementation of the interface and inject it into your class.. the mocked implementation will return you the data that you want to test based on various conditions.
I would suggest you look at mocking frameworks like moq.
Since it has business logic you could probably move that to a separate class that represents what it is doing. then your repo could still be the interface but you will moq the data that will be used by your new class..
Upvotes: 2
Reputation: 364279
There is no way to unit test repository code. Repository code wraps data access so the only reasonable test is integration against real database = no mocking or faking but executing the real code and evaluating that it returned correct results from a testing database.
Upvotes: 1