Ric*_*lay 268 c# parameters moq ref out
是否可以使用Moq(3.0+)分配out
/ ref
参数?
我看过使用Callback()
,但Action<>
不支持ref参数,因为它基于泛型.我也最好It.Is
在ref
参数的输入上放置一个约束(),尽管我可以在回调中做到这一点.
我知道Rhino Mocks支持这个功能,但我正在研究的项目已经在使用Moq了.
Cra*_*ste 300
对于'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);
}
Run Code Online (Sandbox Code Playgroud)
我猜测当你调用安装程序并记住它时,Moq会查看'expectedValue'的值.
因为ref
,我也在寻找答案.
我发现以下QuickStart指南很有用:https: //github.com/Moq/moq4/wiki/Quickstart
sta*_*ica 94
虽然问题是关于Moq 3(可能是由于其年龄),但请允许我发布Moq 4.8的解决方案,该解决方案对by-ref参数的支持有了很大改进.
public 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);
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句:out
也适用于C#7 It.Ref<T>.IsAny
参数(因为它们也是by-ref).
Sco*_*ner 84
编辑:在Moq 4.10中,您现在可以将具有out或ref参数的委托直接传递给Callback函数:
mock
.Setup(x=>x.Method(out d))
.Callback(myDelegate)
.Returns(...);
Run Code Online (Sandbox Code Playgroud)
您将必须定义委托并实例化它:
...
.Callback(new MyDelegate((out decimal v)=>v=12m))
...
Run Code Online (Sandbox Code Playgroud)
对于4.10之前的Moq版本:
Avner Kashtan在他的博客中提供了一种扩展方法,允许从回调中设置out参数: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>;
}
}
Run Code Online (Sandbox Code Playgroud)
使用上面的扩展方法,您可以使用out参数测试接口,例如:
public interface IParser
{
bool TryParse(string token, out int value);
}
Run Code Online (Sandbox Code Playgroud)
..使用以下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);
}
Run Code Online (Sandbox Code Playgroud)
编辑:要支持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;
}
Run Code Online (Sandbox Code Playgroud)
这允许测试接口,例如:
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);
}
Run Code Online (Sandbox Code Playgroud)
Kos*_*sau 48
这是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);
Run Code Online (Sandbox Code Playgroud)
Gis*_*shu 17
似乎不可能开箱即用.看起来有人尝试解决方案
请参阅此论坛帖子 http://code.google.com/p/moq/issues/detail?id=176
此问题 用Moq验证参考参数的值
Mar*_*ijn 15
在 Billy Jakes awnser 的基础上,我创建了一个带有 out 参数的完全动态的模拟方法。我把这个贴在这里给任何觉得有用的人。
// 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);
Run Code Online (Sandbox Code Playgroud)
Red*_*ood 14
在 VS2022 中你可以简单地执行以下操作:
foo.Setup(e => e.TryGetValue(out It.Ref<ExampleType>.IsAny))
.Returns((ref ExampleType exampleType) => {
exampleType = new ExampleType();
return true;
})
Run Code Online (Sandbox Code Playgroud)