views:

59

answers:

2

Hi, 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  

}
+7  A: 

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   

}
fletcher
Thanks Fletcher. I tried this and didnt seem to work still, although I figured out the issue as below, by returning type of ITotalRow from the r => r.TotalRow call.Cheers.
Matt
Fletchers answer in combination with my edit below, resolved the problem. Thanks.
Matt
A: 

Changing the interface declaration from

MarketTotalRow TotalRow { get; } 

to...

ITotalRow TotalRow { get; }

fixed the problem.

Matt
You'll still need to use the Object property of the Mock<ITotalRow> object in the Returns function :)
fletcher