Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...