Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

c# - Linq .FirstOrDefault() on a Mocked List

I'm trying to write a unit test using Moq for some code and coming up against a NullReferenceException on my call to firstOrDefault(). Here is a snippet of my affected code:

    [TestMethod]
    public void LinqAlist()
    {
        var _mockList = new Mock<List<int>>();
        var realData = new List<int>() {1, 2, 3};

        _mockList.Object.AddRange(realData);
        //returns 1
         var realOne = realData.FirstOrDefault(x => x == 1);
        //throws NullReferenceException
        var mockOne = _mockList.Object.FirstOrDefault(x => x == 1);

    }

I can't see why I'm getting the Null reference, as far as I can tell, I've instantiated it properly.

Thanks for your help!

Why am I mocking a list?

I am attempting to mock the behaviour of a Class which inherits from List as follows:

public class IndxList<T> : List<T>.....

public class ClassUnderTest<T> : IndxList<T>....

I'm trying to debug down to the cause of my null to the List class.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to be carefull when you mock a class as there are some more traps. You cannot mock an non virtual method with this framework and even with others the base method will still be executed.

When you mock a type it should be about simplifying the dependencies needed to test an other part. Also that you only test the specific part which the unit test is about.

With a list it is easier to just create one. You can assume that this class is tested and working.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...