繁体   English   中英

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

[英]Mocked object returning null object instead of List

使用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();行抛出异常salesImportResults.Count = sales.Count();

public interface ISalesParser
{
    IEnumerable<ImportedData> Parse(string data);
}

你打电话时

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++);

Object 返回任务时不可等待<object>而不是列表<div id="text_translate"><p>我有这个方法应该只返回一个项目 object。IntelliSense 告诉我更新它以返回一个 Task<List> 但是我必须更改属性的声明(我想确认只返回一个项目,因此 the.Result.First() 但是我收到一条错误消息,指出 Project is not awaitable。</p><pre> public async Task<Project> GetProjectDataAsync(int projectId) { return await _db.LoadData<Project, dynamic>("dbo.Sp_Get_Project_Data_By_ProjectId", new { projectId }, ConnectionStringName, true).Result.First(); }</pre><p> 这是电话:</p><pre> public Project Project { get; set; } public async Task OnGetAsync(int projectId) { Project = await _db.GetProjectDataAsync(projectId); }</pre><p> 如果值得注意,我正在使用 Dapper 连接到具有以下 LoadData 定义的数据库:</p><pre> public async Task<List<T>> LoadData<T, U>(string sqlStatement, U parameters, string connectionStringName, bool isStoredProcedure = false) { string connectionString = _config.GetConnectionString(connectionStringName);. CommandType commandType = CommandType;Text. if (isStoredProcedure == true) { commandType = CommandType;StoredProcedure. } using (IDbConnection connection = new SqlConnection(connectionString)) { var rows = await connection,QueryAsync<T>(sqlStatement, parameters: commandType; commandType). return rows;ToList(); } }</pre></div></object>

[英]Object not awaitable when returning Task<object> instead of List

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 模拟的存储库返回的对象具有空属性 模拟 DbSet 不返回对象 从部分模拟对象返回模拟对象不起作用 为什么我的嘲笑对象没有返回结果? 反序列化xml以列出返回null的对象 C#列表计数返回对象为null 模拟控制器返回 NULL 模拟接口返回 null Object 返回任务时不可等待<object>而不是列表<div id="text_translate"><p>我有这个方法应该只返回一个项目 object。IntelliSense 告诉我更新它以返回一个 Task<List> 但是我必须更改属性的声明(我想确认只返回一个项目,因此 the.Result.First() 但是我收到一条错误消息,指出 Project is not awaitable。</p><pre> public async Task<Project> GetProjectDataAsync(int projectId) { return await _db.LoadData<Project, dynamic>("dbo.Sp_Get_Project_Data_By_ProjectId", new { projectId }, ConnectionStringName, true).Result.First(); }</pre><p> 这是电话:</p><pre> public Project Project { get; set; } public async Task OnGetAsync(int projectId) { Project = await _db.GetProjectDataAsync(projectId); }</pre><p> 如果值得注意,我正在使用 Dapper 连接到具有以下 LoadData 定义的数据库:</p><pre> public async Task<List<T>> LoadData<T, U>(string sqlStatement, U parameters, string connectionStringName, bool isStoredProcedure = false) { string connectionString = _config.GetConnectionString(connectionStringName);. CommandType commandType = CommandType;Text. if (isStoredProcedure == true) { commandType = CommandType;StoredProcedure. } using (IDbConnection connection = new SqlConnection(connectionString)) { var rows = await connection,QueryAsync<T>(sqlStatement, parameters: commandType; commandType). return rows;ToList(); } }</pre></div></object> Automapper 中的对象返回 null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM