Mocking objects with complex Lambda Expressions as parameters

Posted by iCe on Stack Overflow See other posts from Stack Overflow or by iCe
Published on 2010-04-26T13:52:55Z Indexed on 2010/04/26 13:53 UTC
Read the original article Hit count: 308

Filed under:
|
|
|
|

Hi there,

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. (Moq fails with NotSupportedException, and in RhinoMocks simpy does not satisgy expectation).

This is simplified example of what I´m trying to do:

  1. I have a Calculator object that does calculations:

    public class Calculator
    {
         public 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;
     }
    
    }
  2. I need to validate parameters on every method in the Calculator class, so to keep with the Single Responsability 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&lt;Calculator, Func&lt;int, int, int&gt;&gt; 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; }
    
    }
  3. Now, 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&lt;ICalculatorProxy&gt;();
    
    
    calculatorProxyMock.Expect(x =&gt; x.Calculator).Return(_calculator);
    
    
    calculatorProxyMock.Expect(x =&gt; x.Operation(c =&gt; c.Add, 2, 2)).Return(4);
    
    
    var mathParser = new MathParser(calculatorProxyMock);
    
    
    mathParser.ProcessExpression("2 + 2");
    
    
    calculatorProxyMock.VerifyAllExpectations();
    
    }

However I cannot get it to work!

Any ideas about how this can be done?

Thanks a lot!

© Stack Overflow or respective owner

Related posts about c#

Related posts about mocking