暂时将 MockRepository 放在一边,我创建了一个继承自的类,Mock
以提供您所追求的功能。一、用法(XUnit语法):
[Fact]
public void SomeTest()
{
var mock = new Mock2<IDependency>();
var sut = new Sut(mock.Object);
mock.SetupAndExpect(d => d.DoSomething(It.IsAny<string>(), It.IsAny<long>()),Times.Once).Returns(3);
mock.SetupAndExpect(d => d.DoSomethingNoReturn(It.IsAny<string>()), Times.Once);
mock.SetupAndExpect(d => d.DoSomethingNoReturn(It.IsAny<string>()), Times.Once);
sut.CallDoSomething();
mock.VerifyAllExpectations();
}
该SetupAndExpect
方法是Setup
允许Times
通过的替代方法。VerifyAllExpectations
相当于VerifyAll
。_ 如果你愿意,你可以摆弄这些名字。
该类Mock2
存储expression
并在 期间times
传递以SetupAndExpect
供以后使用VerifyAllExpectations
。
在我展示Mock2
代码并讨论MockRepository
解决方案之前,先解释一下冗长的内容。让它适用于没有返回值的模拟方法是相当容易的,因为表达式都有一个比模拟类型更通用的类型。但是,对于具有返回值的方法,要调用的基础验证是Mock.Verify<TResult>(...)
. 为了能够在VerifyAllExpectations
我最终使用反射期间绑定到正确关闭的方法。我确信修改 Mock 本身以放入此功能将允许一个不那么 hacky 的解决方案。
现在,回到存储库:我的想法是修改Mock2
,而不是继承自Mock
,它接受一个实例Mock
作为构造函数参数并使用它来调用Setup
and Verify
。MockRepository
然后,您可以在( ??)上编写一个新的扩展方法,该方法Create2
调用原始实例MockRepository.Create
并将创建的Mock
实例传递给实例的构造函数,Mock2
然后将其返回。
SetupAndExpect
最后一个替代VerifyAllExpectations
方法是在Mock
. 但是,期望信息的存储可能必须处于某种静态状态并面临清理问题。
这是Mock2
代码:
public class Mock2<T> : Mock<T> where T:class
{
private readonly Dictionary<Type, List<Tuple<Expression,Func<Times>>>> _resultTypeKeyedVerifications =
new Dictionary<Type, List<Tuple<Expression, Func<Times>>>>();
private readonly List<Tuple<Expression<Action<T>>, Func<Times>>> _noReturnTypeVerifications =
new List<Tuple<Expression<Action<T>>, Func<Times>>>();
public ISetup<T, TResult> SetupAndExpect<TResult>(Expression<Func<T, TResult>> expression, Func<Times> times)
{
// Store the expression for verifying in VerifyAllExpectations
var verificationsForType = GetVerificationsForType(typeof(TResult));
verificationsForType.Add(new Tuple<Expression, Func<Times>>(expression, times));
// Continue with normal setup
return Setup(expression);
}
public ISetup<T> SetupAndExpect(Expression<Action<T>> expression, Func<Times> times)
{
_noReturnTypeVerifications.Add(new Tuple<Expression<Action<T>>, Func<Times>>(expression, times));
return Setup(expression);
}
private List<Tuple<Expression, Func<Times>>> GetVerificationsForType(Type type)
{
// Simply gets a list of verification info for a particular return type,
// creating it and putting it in the dictionary if it doesn't exist.
if (!_resultTypeKeyedVerifications.ContainsKey(type))
{
var verificationsForType = new List<Tuple<Expression, Func<Times>>>();
_resultTypeKeyedVerifications.Add(type, verificationsForType);
}
return _resultTypeKeyedVerifications[type];
}
/// <summary>
/// Use this instead of VerifyAll for setups perfomed using SetupAndRespect
/// </summary>
public void VerifyAllExpectations()
{
VerifyAllWithoutReturnType();
VerifyAllWithReturnType();
}
private void VerifyAllWithoutReturnType()
{
foreach (var noReturnTypeVerification in _noReturnTypeVerifications)
{
var expression = noReturnTypeVerification.Item1;
var times = noReturnTypeVerification.Item2;
Verify(expression, times);
}
}
private void VerifyAllWithReturnType()
{
foreach (var typeAndVerifications in _resultTypeKeyedVerifications)
{
var returnType = typeAndVerifications.Key;
var verifications = typeAndVerifications.Value;
foreach (var verification in verifications)
{
var expression = verification.Item1;
var times = verification.Item2;
// Use reflection to find the Verify method that takes an Expression of Func of T, TResult
var verifyFuncMethod = GetType()
.GetMethods(BindingFlags.Instance | BindingFlags.Public)
.Single(IsVerifyMethodForReturnTypeAndFuncOfTimes)
.MakeGenericMethod(returnType);
// Equivalent to Verify(expression, times)
verifyFuncMethod.Invoke(this, new object[] {expression, times});
}
}
}
private static bool IsVerifyMethodForReturnTypeAndFuncOfTimes(MethodInfo m)
{
if (m.Name != "Verify") return false;
// Look for the single overload with two funcs, which is the one we want
// as we're looking at verifications for functions, not actions, and the
// overload we're looking for takes a Func<Times> as the second parameter
var parameters = m.GetParameters();
return parameters.Length == 2
&& parameters[0] // expression
.ParameterType // Expression
.GenericTypeArguments[0] // Func
.Name == "Func`2"
&& parameters[1] // times
.ParameterType // Func
.Name == "Func`1";
}
}
最后警告:这只是轻微测试,不会同时测试。它没有等效于Verify
that takeTimes
而不是Func<Times>
. 可能有一些更好的方法名称和/或原因,为什么这通常都是一个坏主意。
我希望它对您或某人有用!