簡體   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