【问题标题】:Is it possible to return a mock from another mock using Moq in C#?是否可以在 C# 中使用 Moq 从另一个模拟返回模拟?
【发布时间】:2023-04-05 17:54:02
【问题描述】:

我使用 Moq 作为我的模拟框架。根据下面的代码,我有两个模拟设置,我想设置第二个来返回第一个模拟。这可能吗?如果可以,我将如何去做?目前它说返回的模拟是无效的候选人。

[SetUp]
private void SetupMarketRow()
{
   var marketTotalRow = new Mock<ITotalRow>();
   marketTotalRow.Setup(r => r.TotalBudgetCurrentFact).Returns(1860716);
   marketTotalRow.Setup(r => r.TotalBudgetEvol).Returns(-26);
   marketTotalRow.Setup(r => r.TotalBudgetPreviousFact).Returns(2514079);


   var localMarketReport = new Mock<IReport>();
   localMarketReport.Setup(r => r.TotalRow).Returns(marketTotalRow);  
   // Red swiggley here saying invalid candidate  

}

【问题讨论】:

    标签: c# unit-testing mocking moq


    【解决方案1】:

    您可以使用 marketTotalRow.Object 访问实际的 Mocked ITotalRow。

    [SetUp] 
    private void SetupMarketRow() 
    { 
       var marketTotalRow = new Mock<ITotalRow>(); 
       marketTotalRow.Setup(r => r.TotalBudgetCurrentFact).Returns(1860716); 
       marketTotalRow.Setup(r => r.TotalBudgetEvol).Returns(-26); 
       marketTotalRow.Setup(r => r.TotalBudgetPreviousFact).Returns(2514079); 
    
    
       var localMarketReport = new Mock<IReport>(); 
       localMarketReport.Setup(r => r.TotalRow).Returns(marketTotalRow.Object);   
       // Red swiggley here saying invalid candidate   
    
    }
    

    【讨论】:

    • 谢谢弗莱彻。我尝试了这个,但似乎仍然没有工作,尽管我通过从 r => r.TotalRow call.Cheers 返回 ITotalRow 的类型来解决如下问题。
    • 弗莱彻的回答结合我在下面的编辑,解决了这个问题。谢谢。
    【解决方案2】:

    更改接口声明
    MarketTotalRow TotalRow { get; } 
    

    到...

    ITotalRow TotalRow { get; }
    

    解决了问题。

    【讨论】:

    • 您仍然需要在 Returns 函数中使用 Mock 对象的 Object 属性 :)
    猜你喜欢
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多