是否可以在C#中使用Moq从另一个模拟返回模拟?

时间:2010-08-09 13:10:40

标签: c# unit-testing mocking moq

我使用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  

}

2 个答案:

答案 0 :(得分:10)

您可以使用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   

}

答案 1 :(得分:0)

更改界面声明
MarketTotalRow TotalRow { get; } 

为...

ITotalRow TotalRow { get; }

修复了问题。