是否可以使用 Moq(3.0+)分配 out
/ref
参数?
我已经尝试过使用 Callback()
,但是因为它基于泛型,所以 Action<>
不支持 ref 参数。我还想在 ref
参数的输入上加上一个约束(It.Is
),尽管我可以在回调函数中实现这一点。
我知道 Rhino Mocks 支持这个功能,但我们的项目已经在使用 Moq 了。
是否可以使用 Moq(3.0+)分配 out
/ref
参数?
我已经尝试过使用 Callback()
,但是因为它基于泛型,所以 Action<>
不支持 ref 参数。我还想在 ref
参数的输入上加上一个约束(It.Is
),尽管我可以在回调函数中实现这一点。
我知道 Rhino Mocks 支持这个功能,但我们的项目已经在使用 Moq 了。
对于'out',下面的方法在我的情况下似乎可以工作。
public interface IService
{
void DoSomething(out string a);
}
[TestMethod]
public void Test()
{
var service = new Mock<IService>();
var expectedValue = "value";
service.Setup(s => s.DoSomething(out expectedValue));
string actualValue;
service.Object.DoSomething(out actualValue);
Assert.AreEqual(expectedValue, actualValue);
}
我猜想Moq在调用Setup时会查看“expectedValue”的值并记住它。
至于ref
,我也在寻找答案。
我发现以下快速入门指南很有用:https://github.com/Moq/moq4/wiki/Quickstart
Setup
方法中没有分配输出或引用参数的方法。 - Richard Szalayout
参数类型是一个类而不是像字符串这样内置的类型 - 我不认为这会起作用。今天我尝试了一下。模拟对象模拟调用,并通过“out”参数返回空。 - azheglovout
参数。你确定你的 Setup
被正确匹配了吗?否则,如果你有一个松散的模拟对象,当没有相关的 Setup
时,它可能会使用默认行为。如果你想确保 Moq 不会因为决定没有匹配到 Setup
就回退到空实现,请使用 MockBehavior.Strict
。 - Jeppe Stig Nielsen=>
将__闭合__或__捕获__局部变量expectedValue
。不会有作用域问题。Moq框架可以检查表达式树,并找到捕获变量的值。 - Jeppe Stig Nielsenpublic interface IGobbler
{
bool Gobble(ref int amount);
}
delegate void GobbleCallback(ref int amount); // needed for Callback
delegate bool GobbleReturns(ref int amount); // needed for Returns
var mock = new Mock<IGobbler>();
mock.Setup(m => m.Gobble(ref It.Ref<int>.IsAny)) // match any value passed by-ref
.Callback(new GobbleCallback((ref int amount) =>
{
if (amount > 0)
{
Console.WriteLine("Gobbling...");
amount -= 1;
}
}))
.Returns(new GobbleReturns((ref int amount) => amount > 0));
int a = 5;
bool gobbleSomeMore = true;
while (gobbleSomeMore)
{
gobbleSomeMore = mock.Object.Gobble(ref a);
}
out
参数无效,对吗? - ATD编辑: 在Moq 4.10中,现在可以直接将具有out或ref参数的委托传递给Callback函数:
mock
.Setup(x=>x.Method(out d))
.Callback(myDelegate)
.Returns(...);
你需要定义一个委托并实例化它:
...
.Callback(new MyDelegate((out decimal v)=>v=12m))
...
对于Moq 4.10之前的版本:
Avner Kashtan在他的博客中提供了一个扩展方法,允许从回调函数中设置输出参数:Moq、Callbacks和Out参数:一个特别棘手的边缘情况
这个解决方案既优雅又hacky。它的优雅之处在于提供了一种流畅的语法,感觉与其他Moq回调相得益彰。而它的hacky之处则在于依赖于通过反射调用一些内部的Moq API。
上面链接中提供的扩展方法没有编译通过,因此我提供了下面的编辑版本。您将需要为每个输入参数数量创建一个签名;我提供了0和1,但进一步扩展应该很简单:
public static class MoqExtensions
{
public delegate void OutAction<TOut>(out TOut outVal);
public delegate void OutAction<in T1,TOut>(T1 arg1, out TOut outVal);
public static IReturnsThrows<TMock, TReturn> OutCallback<TMock, TReturn, TOut>(this ICallback<TMock, TReturn> mock, OutAction<TOut> action)
where TMock : class
{
return OutCallbackInternal(mock, action);
}
public static IReturnsThrows<TMock, TReturn> OutCallback<TMock, TReturn, T1, TOut>(this ICallback<TMock, TReturn> mock, OutAction<T1, TOut> action)
where TMock : class
{
return OutCallbackInternal(mock, action);
}
private static IReturnsThrows<TMock, TReturn> OutCallbackInternal<TMock, TReturn>(ICallback<TMock, TReturn> mock, object action)
where TMock : class
{
mock.GetType()
.Assembly.GetType("Moq.MethodCall")
.InvokeMember("SetCallbackWithArguments", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, mock,
new[] { action });
return mock as IReturnsThrows<TMock, TReturn>;
}
}
使用上述扩展方法,您可以测试具有输出参数的接口,例如:
public interface IParser
{
bool TryParse(string token, out int value);
}
..使用以下Moq设置:
[TestMethod]
public void ParserTest()
{
Mock<IParser> parserMock = new Mock<IParser>();
int outVal;
parserMock
.Setup(p => p.TryParse("6", out outVal))
.OutCallback((string t, out int v) => v = 6)
.Returns(true);
int actualValue;
bool ret = parserMock.Object.TryParse("6", out actualValue);
Assert.IsTrue(ret);
Assert.AreEqual(6, actualValue);
}
编辑:为了支持void-return方法,你只需要添加新的重载方法:
public static ICallbackResult OutCallback<TOut>(this ICallback mock, OutAction<TOut> action)
{
return OutCallbackInternal(mock, action);
}
public static ICallbackResult OutCallback<T1, TOut>(this ICallback mock, OutAction<T1, TOut> action)
{
return OutCallbackInternal(mock, action);
}
private static ICallbackResult OutCallbackInternal(ICallback mock, object action)
{
mock.GetType().Assembly.GetType("Moq.MethodCall")
.InvokeMember("SetCallbackWithArguments", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, mock, new[] { action });
return (ICallbackResult)mock;
}
public interface IValidationRule
{
void Validate(string input, out string message);
}
[TestMethod]
public void ValidatorTest()
{
Mock<IValidationRule> validatorMock = new Mock<IValidationRule>();
string outMessage;
validatorMock
.Setup(v => v.Validate("input", out outMessage))
.OutCallback((string i, out string m) => m = "success");
string actualMessage;
validatorMock.Object.Validate("input", out actualMessage);
Assert.AreEqual("success", actualMessage);
}
var methodCall = mock.GetType().GetProperty("Setup").GetValue(mock); mock.GetType().Assembly.GetType("Moq.MethodCall").InvokeMember("SetCallbackResponse", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, methodCall, new[] { action });
。 - mike mckechniemock.Setup(x=>x.Method(out d)).Callback(myDelegate).Returns(...);
你需要定义一个委托并进行实例化:...Callback(new MyDelegate((out decimal v)=>v=12m))...;
- esteuart这是从 Moq 网站 获取的文档:
// out arguments
var outString = "ack";
// TryParse will return true, and the out argument will return "ack", lazy evaluated
mock.Setup(foo => foo.TryParse("ping", out outString)).Returns(true);
// ref arguments
var instance = new Bar();
// Only matches if the ref argument to the invocation is the same instance
mock.Setup(foo => foo.Submit(ref instance)).Returns(true);
在Billy Jakes的答案基础上,我创建了一个带有输出参数的完全动态的模拟方法。我将其发布在这里,以供任何发现它有用的人使用。
// Define a delegate with the params of the method that returns void.
delegate void methodDelegate(int x, out string output);
// Define a variable to store the return value.
bool returnValue;
// Mock the method:
// Do all logic in .Callback and store the return value.
// Then return the return value in the .Returns
mockHighlighter.Setup(h => h.SomeMethod(It.IsAny<int>(), out It.Ref<int>.IsAny))
.Callback(new methodDelegate((int x, out int output) =>
{
// do some logic to set the output and return value.
output = ...
returnValue = ...
}))
.Returns(() => returnValue);
看起来这个功能无法直接实现。似乎有人尝试过解决方案。
可以查看这个论坛帖子: http://code.google.com/p/moq/issues/detail?id=176
还可以看看这个问题: Verify value of reference parameter with Moq
在VS2022中,您可以简单地执行以下操作:
foo.Setup(e => e.TryGetValue(out It.Ref<ExampleType>.IsAny))
.Returns((ref ExampleType exampleType) => {
exampleType = new ExampleType();
return true;
})
out
参数也适用,并且不需要显式的委托定义! - undefined delegate void MockOutDelegate(string s, out int value);
public void SomeMethod()
{
....
int value;
myMock.Setup(x => x.TryDoSomething(It.IsAny<string>(), out value))
.Callback(new MockOutDelegate((string s, out int output) => output = userId))
.Returns(true);
}
userId
是什么意思?你模拟方法返回的就是这个值吗? - devklick
public static class MoqExtensions
{
public static IReturnsResult<TMock> DelegateReturns<TMock, TReturn, T>(this IReturnsThrows<TMock, TReturn> mock, T func) where T : class
where TMock : class
{
mock.GetType().Assembly.GetType("Moq.MethodCallReturn`2").MakeGenericType(typeof(TMock), typeof(TReturn))
.InvokeMember("SetReturnDelegate", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, mock,
new[] { func });
return (IReturnsResult<TMock>)mock;
}
}
然后声明一个与待模拟方法签名匹配的自己的委托,并提供自己的方法实现。
public delegate int MyMethodDelegate(int x, ref int y);
[TestMethod]
public void TestSomething()
{
//Arrange
var mock = new Mock<ISomeInterface>();
var y = 0;
mock.Setup(m => m.MyMethod(It.IsAny<int>(), ref y))
.DelegateReturns((MyMethodDelegate)((int x, ref int y)=>
{
y = 1;
return 2;
}));
}
今天下午我花了一个小时来解决这个问题,但是无论在哪里都找不到答案。后来我自己试着操作之后,终于找到了一个对我有效的解决方案。
string firstOutParam = "first out parameter string";
string secondOutParam = 100;
mock.SetupAllProperties();
mock.Setup(m=>m.Method(out firstOutParam, out secondOutParam)).Returns(value);
mock.SetupAllProperties();
,它会为您存根所有属性。这可能不适用于每个测试用例场景,但如果您只关心获取YourMethod
的return value
,那么这将很好地发挥作用。
It.IsAny<T>()
类似的匹配器 (ref It.Ref<T>.IsAny
) 到支持通过自定义委托类型匹配方法签名来设置.Callback()
和.Returns()
。同样支持受保护的方法。请参见例如下面 我的回答。 - stakx - no longer contributing