基于此gist https://gist.github.com/christothes/7d57db1d16c96669ecd0218ab056a422你可以创建一个重载SetupDefaultArgs
这适用于void
返回类型。您需要添加对Moq.Language.Flow
and System.Linq.Expressions;
public static ISetup<T> SetupDefaultArgs<T>(this Mock<T> mock, string methodName)
where T : class
{
var method = typeof(T).GetMethod(methodName);
if (method == null)
throw new ArgumentException($"No method named '{methodName}' exists on type '{typeof(T).Name}'");
var instance = Expression.Parameter(typeof(T), "m");
var callExp = Expression.Call(instance, method, method.GetParameters().Select(p => GenerateItIsAny(p.ParameterType)));
var exp = Expression.Lambda<Action<T>>(callExp, instance);
return mock.Setup(exp);
}
//helper method for above
private static MethodCallExpression GenerateItIsAny(Type T)
{
var ItIsAnyT = typeof(It)
.GetMethod("IsAny")
.MakeGenericMethod(T);
return Expression.Call(ItIsAnyT);
}
因此,在您的情况下,用法将如下所示:
public interface IWorkClient
{
void DoSomething(string itemName, int itemCount,
ServiceClientCredential cred,
CancellationToken token = default(CancellationToken));
}
var mock = new Mock<IWorkClient>();
mock.SetupDefaultArgs(nameof(IWorkClient.DoSomething));
要确保它已被调用,您可以执行以下操作:
//Arrange
var mock = new Mock<IWorkClient>();
mock.SetupDefaultArgs(nameof(IWorkClient.DoSomething))
.Callback(() => Console.WriteLine("DoSomething has been called"));
var cts = new CancellationTokenSource();
//Act
mock.Object.DoSomething("1", 2, null, cts.Token);
//Assert
mock.Verify(client => client.DoSomething("1", 2, null, cts.Token), Times.Once);