I´m encountering this problem trying to mock some objects that receive complex lambda expressions in my projects. Mostly with with proxy objects that receive this type of delegate:
Func<Tobj, Fun<TParam1, TParam2, TResult>>
I have tried to use Moq as well as RhinoMocks to acomplish mocking those types of objects, however both fail.
This is simplified example of what I´m trying to do: first, I have a Calculator object that does calculations:
public class Calculator
{
public int Add(int x, int y)
{
var result = x + y;
return result;
}
public int Substract(int x, int y)
{
var result = x - y;
return result;
}
}
Next, I need to validate parameters on every method in the Calculator class, so to keep with the Single Responsibility principle, I create a validator class. I wire everything up using a Proxy class, that prevents having duplicate code:
public class CalculatorProxy : CalculatorExample.ICalculatorProxy
{
private ILimitsValidator _validator;
public CalculatorProxy(Calculator _calc, ILimitsValidator _validator)
{
this.Calculator = _calc;
this._validator = _validator;
}
public int Operation(Func<Calculator, Func<int, int, int>> operation,
int x,
int y)
{
_validator.ValidateArgs(x, y);
var calcMethod = operation(this.Calculator);
var result = calcMethod(x, y);
_validator.ValidateResult(result);
return result;
}
public Calculator Calculator { get; private set; }
}
Finally, I´m testing a component that does use the CalculatorProxy, so I want to mock it, for example using Rhino Mocks:
[TestMethod]
public void ParserWorksWithCalcultaroProxy()
{
var calculatorProxyMock = MockRepository.GenerateMock<ICalculatorProxy>();
calculatorProxyMock.Expect(x => x.Calculator).Return(_calculator);
calculatorProxyMock.Expect(x => x.Operation(c => c.Add, 2, 2)).Return(4);
var mathParser = new MathParser(calculatorProxyMock);
mathParser.ProcessExpression("2 + 2");
calculatorProxyMock.VerifyAllExpectations();
}
However I cannot get it to work! Moq fails with NotSupportedException, and in RhinoMocks simpy it never gets to satisfy the expectations.