Am I missing something when trying to mock out a linq query?

1,051 views
Skip to first unread message

Lee Prosser

unread,
Jul 1, 2015, 5:10:41 PM7/1/15
to nsubs...@googlegroups.com
So in the real world I have something which returns an IEnumerable then an Any query happens to it then some other logic occurs, but I was struggling to mock out the query.

Here is an example of me isolating the use case

[Test]
        public void dummy_test()
        {
            var mockEnumerable = Substitute.For<IEnumerable<int>>();
            mockEnumerable.Any(Arg.Any<Func<int, bool>>()).Returns(x => true);

            var res = mockEnumerable.Any(x => x == 10);
            Assert.That(res, Is.True);
        }


So I thought that would be fine, but it just blows up on the stubbing the any field with 


System.ArgumentNullException : Value cannot be null.


Parameter name: predicate

I have tried just doing .Any(x => true).ReturnsWithAnyArg(x => true); but that blows up too.

So is there a special way to mock out linq queries on an object?

David Tchepak

unread,
Jul 1, 2015, 6:17:37 PM7/1/15
to nsubs...@googlegroups.com
`Any` is an extension method on `IEnumerable<T>`. NSubstitute can't mock extension methods.

I don't think I ever substitute for `IEnumerable<T>`, I use real collections instead. For example:

    mySub.Widgets.Returns(new [] { new Widget(1), new Widget(2) });

If you can give a bit more info about the scenario you are trying to test I'm happy to try to come up with some ideas on how to test it.

Regards,
David


--
You received this message because you are subscribed to the Google Groups "NSubstitute" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nsubstitute...@googlegroups.com.
To post to this group, send email to nsubs...@googlegroups.com.
Visit this group at http://groups.google.com/group/nsubstitute.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages