Created
April 29, 2014 22:17
-
-
Save NigelThorne/96badd3ba9a18d084cd8 to your computer and use it in GitHub Desktop.
Extension to Moq to allow you to write: Mock.Get(obj).VerifyNoMethodsAreCalled();
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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