问题
I am trying to write a unit test for a method which takes an IQueryable collection.
How should I instantiate the collection in my unit test before I pass it to the method for test? This is the default code in my test
IQueryable<Item> Items = null; // TODO: Initialize to an appropriate value
And here is what I tried writing
IQueryable<Item> Items = new IQueryable<Item>; // TODO: Initialize to an appropriate value
Am I making a school boy error?
回答1:
Well, you can use .AsQueryable()
on any typed collection/list/array, however IMO you cannot unit test this, as different query providers support different options/methods. You can only integration-test this. Any unit test (especially one using objects) does little or nothing to prove your system.
回答2:
IQueryable seems to be an interface ( http://msdn.microsoft.com/en-us/library/system.linq.iqueryable.aspx ), shouldn't you try to instanciate a class that implements this interface instead (or maybe use a mock object for your test) ?
回答3:
Best way is to use a pattern that let's you test IQueryable responses from a database such as the Unit of work and repository pattern
The best way to create a mock repository to use in unit testing is with a memory repository, but you can also use Moq or any other fake repository library.
来源:https://stackoverflow.com/questions/6599805/unit-test-iqueryable