Global Custom Match

17 views
Skip to first unread message

Anthony Dewhirst

unread,
Oct 22, 2014, 11:28:19 AM10/22/14
to moq...@googlegroups.com
Is there anyway to set a custom match to be used across all Moq
Or even set a custom IEquator so that we can implement .Equals in a custom way?

I have objects that I want to test using value equality but in the non test code they should use this.
Hope that this makes sense.

Anthony Dewhirst

unread,
Oct 23, 2014, 6:27:54 AM10/23/14
to moq...@googlegroups.com
I have come up with a solution for the moment that works for me. It needs expanding and possibly some more checking, but it generally gives you an answer.

here is the code:

    public static class MoqExtensions
   
{
       
private static IEqualityComparer _equalityComparer;

       
public static void SetEqualityComparer(IEqualityComparer equalityComparer)
       
{
            _equalityComparer
= equalityComparer;
       
}

       
public static ISetup<T> ValueSetup<T>(this Mock<T> mock, Expression<Action<T>> expression)
           
where T : class
       
{
           
var updatedExpression = (Expression<Action<T>>)new MyExpressionVisitor().Visit(expression);
           
return mock.Setup(updatedExpression);
       
}

       
public static T Match<T>(this T instance)
       
{
           
return It.Is<T>(t => _equalityComparer.Equals(instance, t));
       
}

       
private class MyExpressionVisitor : ExpressionVisitor
       
{
           
protected override Expression VisitMember(MemberExpression node)
           
{
               
if(node.Expression.NodeType == ExpressionType.Constant)
               
{
                   
// We have to do this to get access to the base value and not the wrapped value
                   
var param = Expression.Constant(Expression.Lambda(node).Compile().DynamicInvoke());
                   
var call = Expression.Call(typeof(MoqExtensions), "Match", new[] { node.Type }, param);

                   
return call;
               
}

               
return base.VisitMember(node);
           
}
       
}
   
}
Reply all
Reply to author
Forward
0 new messages