Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extension to Moq to allow you to write: Mock.Get(obj).VerifyNoMethodsAreCalled();
public static class MoqExtensions
{
/// <summary>
/// LINQ + Reflection + Moq = MAGIC!!!
/// Calls Mock.Get(obj).Verify(x => x.MethodY(It.IsAny<Z>,...), Times.Never) for all methods
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">mock object you want to assert on</param>
public static void VerifyNoMethodsAreCalled<T>(this Mock<T> mock) where T : class
{
var methods = typeof(T).GetMethods(BindingFlags.Public | BindingFlags.Instance);
var isAny = typeof(It).GetMethod("IsAny", BindingFlags.Public | BindingFlags.Static);
foreach (var @delegate in from methodInfo in methods
let parameterMatchers = methodInfo.GetParameters().Select(p => isAny.MakeGenericMethod(p.ParameterType))
let paramz = parameterMatchers.Select(p => Expression.Call(p, new Expression[0]))
let paramM = Expression.Parameter(typeof (T), "m")
let body = Expression.Call(paramM, methodInfo, paramz)
select Expression.Lambda<Action<T>>(body, paramM))
{
mock.Verify(@delegate, Times.Never);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.