Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to return a mock from another mock using Moq in C#?

I am using Moq as my mocking framework. As per the code below, I have two mocks setup and I would like to setup the second to return the first mock. Is this possible and if so how would I go about doing it? At the moment it says the mock being returned is an invalid candidate.

[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  

}
like image 343
Matt Avatar asked Dec 28 '22 09:12

Matt


1 Answers

You can access the actual Mocked ITotalRow using marketTotalRow.Object.

[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   

}
like image 77
fletcher Avatar answered Dec 31 '22 15:12

fletcher