开发者

Mocking ObjectContext, dealing with ObjectQuery.Include(string) method?

I have been investigating how to decouple my DomainServices from their datasource so I can test them in unit tests. I'm starting to think fully decoupling them is not pos开发者_运维技巧sible.

There is a decent amount of info out there, such as this question and this blog post. The blog post in particular gets you really far into mocking ObjectContext.

But my DomainServices have methods like this:

public IQueryable<Client> GetClients()
{
    return ObjectContext.Clients
        .Include("Foo")
        .Include("Bar")
        .Where(c => c.IsBaz);
}

It doesn't seem possible to fully mock the Include method, as it returns an ObjectQuery<T>, and the Include method is not captured in an interface anywhere (There is no IObjectQuery interface). ObjectQuery implements IQueryable<T>, and so I thought making my own Include method that returns IQueryable would work, but only if I plan to call Include at most once per query.

I am using EF4, .NET 4, Silverlight 4 and RIA Services RTW.

As a bit of a rant, I'm disappointed at how test unfriendly LINQ to Entities and by extension RIA Services is :(


I don't think you should be unit testing at that level. I'm all in for unit tests, but there is a certain point where you need to stop.

Lets say that code is part of a ClientsLinqRepository, which in turns implements IClientsLinqRepository. You mock IClientsLinqRepository, when you implement code that depends on it.

While the above is perfectly valid, ClientsLinqRepository is an integration implementation. Pretty much like if you had IMessageSender and you implemented MailSender. Here you have code that its main responsibility is integrating with a separate system, for you that's the database.

Based on the above scenario, I suggest you do some focused integration tests on that class. So in that case you do want to hit the external system (database), and make sure that integration code is working appropriately with the external system. It'll allow you to quickly identify if anything in the code vs. the database is broken without dealing with the complexity of the rest of the system (which a pain when trying to do integration tests at other levels).

Keep the focused integration tests separate from the unit tests, so you can run the amazingly fast unit tests as much as you want, and run integration test when changes are made to any of the integration pieces and every now and then.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜