开发者

Unit testing EF4 Repository Code

What's 开发者_如何学Ca 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?


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..


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.


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:

  • http://thoughtjelly.wordpress.com/2011/09/22/real-world-unit-testing-queries-against-entity-framework-ef-model-repositories/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜