模拟对象返回null对象而不是List

时间:2014-10-15 19:50:43

标签: c# unit-testing moq

使用Moq,我有一个模拟对象应该从函数调用中返回List<>。返回的对象是null,我不知道为什么。

在这里,我创建了模拟对象并设置函数以返回List

var mockParser = new Mock<ISalesParser>() { CallBase = false };
        mockParser.Setup(m => m.Parse(It.IsAny<string>())).Returns(new List<ImportedData>{ new ImportedData{ ReportingPeriod = DateTime.Now } });

正在测试的功能,我调用Parse()并捕获返回的对象。当我尝试获取列表的Count时,会抛出System.ArgumentNullExcpetion : Value cannot be null例外。

我对嘲笑和Moq很新,有什么我想念的吗?

测试方法:

[Test]
    public void Test_ImportNormalExecution()
    {
        var importedData = new Mock<List<ImportedData>>(MockBehavior.Strict) { CallBase = false };
        importedData.SetupAllProperties();
        importedData.As<IEnumerable<ImportedData>>().Setup(m => m.GetEnumerator()).Returns(importedList.GetEnumerator());

        var mockParser = new Mock<ISalesParser>() { CallBase = false };
        mockParser.Setup(m => m.Parse(It.IsAny<string>())).Returns(new List<ImportedData>{ new ImportedData{ ReportingPeriod = DateTime.Now } });
        mockParser.Setup(m => m.Parse(It.IsAny<string>())).Callback(() => parseFuncCall++);

        var mockContext = new Mock<ApplicationDbContext>() { CallBase = true };
        mockContext.As<IUnitOfWork>().CallBase = false;
        mockContext.Setup(m => m.ImportedData.Add(It.IsAny<ImportedData>())).Callback(() => addImportDataCall++);

        unitOfWork = new UnitOfWork(mockContext.Object);
        dataRepository = new ImportedDataRepository(mockContext.Object);
        parser = mockParser.Object;

        service = new SalesService(parser, dataRepository, unitOfWork);
        string status = "Parsed input file.  Processed imported data into sales history.";
        SalesImportResults results = ((ISalesService)service).Import(AmazonHtmlSalesParserResources.AmazonHtmlDataValid);

        Assert.AreEqual(1, results.Count);
        Assert.That(parseFuncCall == 1);
        Assert.That(addImportDataCall == 1);
        Assert.That(String.Compare(status, results.Status) == 0);

    }

待测方法

public SalesImportResults ISalesService.Import(string data)
    {
        var salesImportResults = new SalesImportResults();

        try
        {
            IEnumerable<ImportedData> sales = _salesParser.Parse(data);

            salesImportResults.Count = sales.Count();
            salesImportResults.Date = sales.FirstOrDefault().ReportingPeriod;
            salesImportResults.Status = "Parsed input file.";

            foreach (ImportedData salesItem in sales)
            {
                _importedDatarepository.Add(salesItem);
            }
            _unitOfWork.SaveChanges();

            salesImportResults.Status += " Inserted data into import table.";

            _importedDatarepository.ProcessImportedData();

            salesImportResults.Status += " Processed imported data into sales history.";

            return salesImportResults;
        }
        catch (Exception ex)
        {
            throw new ApplicationException(salesImportResults.Status + " - but then something went wrong: " + ex.Message, ex);
        }

    }

该行salesImportResults.Count = sales.Count();

上会抛出异常
public interface ISalesParser
{
    IEnumerable<ImportedData> Parse(string data);
}

1 个答案:

答案 0 :(得分:3)

致电时

mockParser.Setup(m => m.Parse(It.IsAny<string>())).Callback(() => parseFuncCall++);

先前配置的返回值被重置,因此它再次为空。如果您需要设置返回值和回调,可以将ReturnsCallback方法链接在一起:

var mockParser = new Mock<ISalesParser>() { CallBase = false };
mockParser.Setup(m => m.Parse(It.IsAny<string>()))
    .Returns(new List<ImportedData>{ new ImportedData{ ReportingPeriod = DateTime.Now } })
    .Callback(() => parseFuncCall++);