Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7755193
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T12:30:25+00:00 2026-06-01T12:30:25+00:00

Method M takes 2 parameters, P1 and P2. P2 is a delegate. I want

  • 0

Method M takes 2 parameters, P1 and P2. P2 is a delegate. I want to tell a mock object, “Whenever method M is called with parameter P1, invoke P2 and pass object O to it.” I’m using Moq.

The following approach works, but seems a bit verbose.

this.DataCacheMock = Mock.Of<IDataCache>();
var dataObject = new DataObject();

Mock.Get(this.DataCacheMock)
.Setup(m => m.GetDataObject(123, It.IsAny<EventHandler<DataPortalResult<DataObject>>>()))
.Callback((int id, EventHandler<DataPortalResult<DataObject>> callback) => callback(null, new DataPortalResult(dataObject, null, null)));

I’d like to refactor that last bit into a generic helper method so that I (and future test authors) would only need to write something like this:

TestTools.ArrangeDataPortalResult(this.DataCacheMock.GetDataObject, 123, dataObject);

The big question is: what would go inside that helper method? I’ve had partial success so far, but I’m wondering if there’s any way to get all the way there.

First Attempt (doesn’t work)

public static void ArrangeDataPortalResult<TMock, TResult, TParam>(
        TMock mockObject,
        Action<TMock, TParam, EventHandler<DataPortalResult<TResult>>> action,
        TParam parameter,
        TResult result)
    where TMock : class
{
    Moq.Mock.Get(mockObject)
        .Setup(m => action(m, parameter, Moq.It.IsAny<EventHandler<DataPortalResult<TResult>>>()))
        .Callback<TParam, EventHandler<DataPortalResult<TResult>>>((p, callback) =>
                callback(null, new DataPortalResult<TResult>(result, null, null)));
}

I can call this method like so:

TestTools.ArrangeDataPortalResult<IDataCache, DataObject, int>(
    this.DataCacheMock,
    (mock, param, handler) => mock.GetDataObject(param, handler),
    dataObjectId,
    dataObject);

As it turns out, Moq doesn’t like what I’m passing to the Setup method. It throws an exception, saying “Expression is not a method invocation”.

Second Attempt

In this approach I do some manipulation of LINQ expressions (which I’ve never done before).

public static void ArrangeDataPortalResult<TMock, TParam, TResult>(
        TMock mockObject,
        Expression<Action<TMock>> methodCall, TResult result)
    where TMock : class
{
    // Get the method that will be called on the mock object, and the method's parameters.
    var methodCallExpression = methodCall.Body as MethodCallExpression;
    var parameters = methodCallExpression.Arguments;

    // Create a new parameter list, and substitute Moq.It.IsAny<EventHandler<DataPortalResult<TResult>>>() for the callback.
    // This is so that the test author doesn't need to write It.IsAny<blah>.
    var newParameters = parameters.Select(p => p).ToList();
    newParameters.RemoveAt(newParameters.Count - 1);
    var isAny = typeof(Moq.It).GetMethod("IsAny").MakeGenericMethod(typeof(EventHandler<DataPortalResult<TResult>>));
    var newCallbackParameterExpression = Expression.Call(null, isAny);
    newParameters.Add(newCallbackParameterExpression);

    // Create a new expression that contains the new IsAny parameter.
    var newMethodCallExpression = Expression.Call(methodCallExpression.Object, methodCallExpression.Method, newParameters);

    // Set up the mock object to expect a method call with the same parameters passed to it, but allow any callback to be passed to it.
    // Additionally, tell the mock object to immediately invoke its callback, and pass the given result to it.
    Moq.Mock.Get(mockObject)
        .Setup(Expression.Lambda<Action<TMock>>(newMethodCallExpression, methodCall.Parameters))
        .Callback<TParam, EventHandler<DataPortalResult<TResult>>>((p, callback) => callback(null, new DataPortalResult<TResult>(result, null, null)));
}

This method can be called like so.

TestTools.ArrangeDataPortalResult<IDataCache, int, DataObject>(
    this.DataCacheMock,
    mock => mock.GetDataObject(123, null),
    dataObject);

This works, and I might settle for something like this if necessary. Unfortunately if I were to accidentally call the wrong method of DataCacheMock (maybe it has an overload that takes a string instead of an int), then I would get a run time error rather than a compile time error.

Third Attempt

public static void ArrangeDataPortalResultMoq<TMock, TParam, TResult>(
        Expression<Action> methodCall, TResult result)
    where TMock : class
{
    // Get the method that will be called on the mock object, and the method's parameters.
    // (This part is the same.)

    // Create a new parameter list, and substitute Moq.It.IsAny<EventHandler<DataPortalResult<TResult>>>() for the callback.
    // (This part is the same.)

    // Create a new expression that contains the new IsAny parameter.
    var newMethodCallExpression = Expression.Call(Expression.Parameter(typeof(TMock), "mock"), methodCallExpression.Method, newParameters);

    // Get the real mock object referred to in the method call.
    var mockObject = Expression.Lambda<Func<TMock>>(methodCallExpression.Object).Compile()();

    // Set up the mock object to expect a method call with the same parameters passed to it, but allow any callback to be passed to it.
    // Additionally, tell the mock object to immediately invoke its callback, and pass the given result to it.
    Moq.Mock.Get(mockObject)
        .Setup(Expression.Lambda<Action<TMock>>(newMethodCallExpression, Expression.Parameter(typeof(TMock), "mock")))
        .Callback<TParam, EventHandler<DataPortalResult<TResult>>>((p, callback) => callback(null, new DataPortalResult<TResult>(result, null, null)));
}

This version gets the mock object from the expression you pass to it, so you don’t have to mention the mock object twice when you call the helper method:

TestTools.ArrangeDataPortalResultMoq<IDataCache, int, ceQryUomsBO>(
    () => this.DataCacheMock.GetDataObject(dataObjectId, null),
    dataObject);

This approach still has the same problem with types though.

I (and future test authors) could probably deal with the verbose syntax mentioned at the top, and we could probably deal with the lesser type safety since the test would just fail. I’d still like to see if this is possible with Moq though; I’ve gone this far down the rabbit hole. 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T12:30:26+00:00Added an answer on June 1, 2026 at 12:30 pm

    In case it helps someone else, I ended up with a solution that allows me to do this:

    TestTools.ArrangeDataPortalResult(
        this.DataCacheMock,
        (param1, callback) => this.DataCacheMock.Object.GetDataObject(param1, callback),
        123,
        dataObject);
    

    This was good enough for me. My solution is below.

    public static void ArrangeDataPortalResult<TMocked, TResult, TParam>(Mock<TMocked> mock, Expression<Action<TParam, EventHandler<DataPortalResult<TResult>>>> expectedMethodCall, TParam parameter, TResult result)
        where TMocked : class
    {
        var methodCallExpr = expectedMethodCall.Body as MethodCallExpression;
        var newMethodCallExpr = TransformAsyncCallForMoq<TMocked, TResult>(methodCallExpr, parameter);
        mock.Setup(newMethodCallExpr)
            .Callback<TParam, EventHandler<DataPortalResult<TResult>>>((p, callback) => callback(null, new DataPortalResult<TResult>(result, null, null)));
    }
    
    private static Expression<Action<TMocked>> TransformAsyncCallForMoq<TMocked, TResult>(MethodCallExpression methodCallExpr, params object[] expectedParameterValues)
    {
        var methodCallParameters = methodCallExpr.Arguments;
    
        /// Transform a method call on a specific object,
        /// e.g. (param1, param2, callback) => MyMockObject.GetData(param1, param2, callback),
        /// into a lambda expression that Moq's Setup method can use, which looks more like this:
        /// m => m.GetData(5, "asdf", /* any event handler */).
        MethodCallExpression newMethodCallExpression = Expression.Call(
            Expression.Parameter(typeof(TMocked), "m"),
            methodCallExpr.Method,
            CreateParameterExpressionsWithAnyCallback(methodCallParameters, expectedParameterValues));
    
        return Expression.Lambda<Action<TMocked>>(newMethodCallExpression, Expression.Parameter(typeof(TMocked), "m"));
    }
    
    
    private static IEnumerable<Expression> CreateParameterExpressionsWithAnyCallback(IEnumerable<Expression> oldParameterExpressions, IEnumerable<object> expectedParameterValues)
    {
        // Given a set of expressions and expected values, returns a new set of expressions that will 
        // allow Moq to set the proper method call expectation. Assumes there will be one more parameter
        // expression (the callback parameter) that has no expected value, and allows any value for it.
    
        var newParameterExpressions = oldParameterExpressions.Zip(expectedParameterValues,
            (paramExpr, paramVal) => Expression.Constant(paramVal, paramExpr.Type) as Expression);
    
        foreach (var expr in newParameterExpressions)
        {
            yield return expr;
        }
    
        var callbackParamExpr = oldParameterExpressions.Last();
        var isAny = typeof(Moq.It).GetMethod("IsAny").MakeGenericMethod(callbackParamExpr.Type);
        yield return Expression.Call(null, isAny) as Expression;
    }
    

    If anyone knows a simpler way to do it, I hope you’ll share. 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to invoke a method that takes a super class as a parameter
list.loadRequestParms(request, 'a', 20); This method takes three parameters a request object. a char an
I have a Java method that takes 3 parameters, and I'd like it to
I have a static method that takes a parameter and returns a class. the
In this case, the Visual Studio designer generates a method which takes the parameter
In Boo, let's say I'm overriding a method that takes a parameter that takes
I have a method which takes an array of strings as parameter and queries
Let's say I have this method: public static object CallMethod(Delegate method, params object[] args)
I want to write an Action which only takes a PerformanceCounterCategory as a parameter.
I'm traversing an object graph and want to pass it a block that will

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.