Unit Test IQueryable

别等时光非礼了梦想. 提交于 2019-12-22 05:16:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!