Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何模拟返回列表的方法<;T>;?_C#_Unit Testing_Moq - Fatal编程技术网

C# 如何模拟返回列表的方法<;T>;?

C# 如何模拟返回列表的方法<;T>;?,c#,unit-testing,moq,C#,Unit Testing,Moq,我有以下方法: public List<ITestKeyword> AddTests(TestEntity testEntity) { var DesignSteps = new List<ITestKeyword>(); foreach (var testCase in testEntity.TestCases) { DesignSteps.AddRange(testCase.GetTestStepKeywords());

我有以下方法:

public List<ITestKeyword> AddTests(TestEntity testEntity)
{
    var DesignSteps = new List<ITestKeyword>();
    foreach (var testCase in testEntity.TestCases)
    {
        DesignSteps.AddRange(testCase.GetTestStepKeywords());
    }
    return DesignSteps;
}
以下是我试图模仿它的方式:

_mockTestHelper
    .Setup(s => s.AddTests(It.IsAny<TestEntity>()))
    .Returns(It.IsAny<List<ITestKeyword>>());
\u mockTestHelper
.Setup(s=>s.AddTests(It.IsAny()))
.Returns(It.IsAny());
但它似乎不起作用。它正在引发空引用异常。我搞不懂。有人能帮忙吗?

试试这个:

var testList = new List<ITestKeyword>();

_mockTestHelper
    .Setup(s => s.AddTests(It.IsAny<TestEntity>()))
    .Returns(testList);
var testList=newlist();
_模拟测试助手
.Setup(s=>s.AddTests(It.IsAny()))
.返回(测试列表);

这样,您就可以随心所欲地填充列表了

返回(newlist())
?您可以模拟一个
列表
?您可能需要将返回类型更改为
IList
Great。它起作用了。。但我不明白怎么做。你介意详细解释一下吗?你正在尝试返回它。IsAny()基本上是说返回此项的任何实例。但是它怎么能返回某个东西的任意实例呢。答案创建了一个实际的对象,每次在测试框架中调用该函数时都会返回该对象。我在模仿方法的输入而不是输出时使用它。例如,告诉一个方法,无论何时传入任何int,都返回指定的值。@Alex解释得很好。我得到了它。谢谢你的时间。
var testList = new List<ITestKeyword>();

_mockTestHelper
    .Setup(s => s.AddTests(It.IsAny<TestEntity>()))
    .Returns(testList);