16

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?

Adrian S
  • 1,007
  • 4
  • 12
  • 26

3 Answers3

26

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • But this will pass a unit test?? -- IQueryable Items = new IQueryable.AsQueryable(); – Adrian S Jul 06 '11 at 18:19
  • 5
    @suggy1982 no I mean you would create an array/list/whatever with your dummy data and use `theList.AsQueryable()` which will work. However, I repeat: our aim is not merely to "pass tests" - it should be feared towards proving something valuable and meaningful about our system. Since `IQueryable` is so different between implementations, mocking/faking this interface proves almost nothing. – Marc Gravell Jul 06 '11 at 18:23
  • Example of Integration test see http://stackoverflow.com/questions/38706864/iqueryable-unit-or-integration-test/38708116#38708116 – Michael Freidgeim Mar 10 '17 at 10:28
  • @MarcGravell, It may be useful to create unit tests and use mocks to validate order and parameters of internal calls as shown in http://stackoverflow.com/questions/13686286/unit-testing-code-using-iqueryable – Michael Freidgeim Mar 10 '17 at 10:31
3

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) ?

phtrivier
  • 13,047
  • 6
  • 48
  • 79
0

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.

Community
  • 1
  • 1
Daniël Tulp
  • 1,745
  • 2
  • 22
  • 51