Linq .FirstOrDefault()在模拟列表上 [英] Linq .FirstOrDefault() on a Mocked List
问题描述
我正在尝试使用Moq编写一些代码的单元测试,并在我对firstOrDefault()的调用上遇到NullReferenceException.这是我受影响的代码的一个片段:
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);
}
据我所知,我看不到为什么我得到了Null引用,我已经正确地实例化了它.
I can't see why I'm getting the Null reference, as far as I can tell, I've instantiated it properly.
感谢您的帮助!
我为什么要嘲笑列表?
我试图模拟从List继承的Class的行为,如下所示:
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>....
我正在尝试调试导致List类为空的原因.
I'm trying to debug down to the cause of my null to the List class.
推荐答案
在模拟类时,您必须格外小心,因为还有更多陷阱. 您无法使用此框架模拟非虚拟方法,即使与其他框架一起使用,基本方法仍将执行.
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.
这篇关于Linq .FirstOrDefault()在模拟列表上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!