是否可以使用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了。
当前回答
在VS2022中,你可以简单地做:
foo.Setup(e => e.TryGetValue(out It.Ref<ExampleType>.IsAny))
.Returns((ref ExampleType exampleType) => {
exampleType = new ExampleType();
return true;
})
其他回答
这是一个解决方案。
[Test]
public void TestForOutParameterInMoq()
{
//Arrange
_mockParameterManager= new Mock<IParameterManager>();
Mock<IParameter > mockParameter= new Mock<IParameter >();
//Parameter affectation should be useless but is not. It's really used by Moq
IParameter parameter= mockParameter.Object;
//Mock method used in UpperParameterManager
_mockParameterManager.Setup(x => x.OutMethod(out parameter));
//Act with the real instance
_UpperParameterManager.UpperOutMethod(out parameter);
//Assert that method used on the out parameter of inner out method are really called
mockParameter.Verify(x => x.FunctionCalledInOutMethodAfterInnerOutMethod(),Times.Once());
}
在VS2022中,你可以简单地做:
foo.Setup(e => e.TryGetValue(out It.Ref<ExampleType>.IsAny))
.Returns((ref ExampleType exampleType) => {
exampleType = new ExampleType();
return true;
})
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);
}
同样的模式也适用于参数。
It.Ref < T >。IsAny也适用于c# 7的参数(因为它们也是by-ref)。
在我简单地创建一个新的“Fake”类的实例来实现您试图Mock的任何接口之前,我在这里的许多建议中苦苦挣扎。然后,您可以简单地使用方法本身设置out参数的值。
对克雷格·塞莱斯特的答案进行了增强,任何人都可以使用它。out参数为IsAny:
public interface IService
{
void DoSomething(out string a);
}
[TestMethod]
public void Test()
{
var service = GetService();
string actualValue;
service.Object.DoSomething(out actualValue);
Assert.AreEqual(expectedValue, actualValue);
}
private IService GetService()
{
var service = new Mock<IService>();
var anyString = It.IsAny<string>();
service.Setup(s => s.DoSomething(out anyString))
.Callback((out string providedString) =>
{
providedString = "SomeValue";
});
return service.Object;
}
如果你的方法也需要返回一些东西,你也可以使用Returns而不是Callback。