Linq .FirstOrDefault() on a Mocked List

十年热恋 提交于 2019-12-13 07:57:14

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/45013575/linq-firstordefault-on-a-mocked-list

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