简体   繁体   中英

How do I override the Contains method of IQueryable during a unit test?

So here's the thing: I've got an app that I'm testing that uses LINQ to Entities (EF4/.NET4). The app binds to an implementation of the Contains method that ignores nulls and, due to the way the database is configured, ignores case. That works great.

However, when I call into the same methods from my unit tests, I'm passing in a fake context which exposes collections with an in-memory implementation of IQueryable. In this case, it's the LINQ to Objects version of Contains that gets brought in and that one cares about null and case.

Now, I could write my application code to check for null and case, but I don't want to affect the SQL that's being generated just so it will work when it's being called from a unit test and SQL is not involved.

What I really want is to provide the correct IQueryable or whatever so that, during a test, I can swap in my own custom Contains implementation that ignores null and case. How do I do that? Thanks!

Compiler will bind to the most derived compile-time type's exthension method.

Even if you pass a mock instance and have a custom implementation of "Contains" extension method to its type on your Unit Test context, you are calling some code that only knows that you provided an IQueriable instance, so it binds to linq to objects version.

Probably you can achieve this by implementing your own QueryProvider but it seems to be an extreme option.

Maybe there is another way if you can use C#4.0 dynamic types.

如果你有一个虚假的上下文,你不能创建一个模拟IQueriable并使用它吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM