是否可以使用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了。
当前回答
就像这样:
被嘲笑的方法是
public bool GenerateClient(out Client client);
那么模拟部分将是:
Client client = new Client();
clintMockBll
.Setup(x => x.GenerateClient(out client))
.Returns((Client client1) =>
{
client = new Client(){Name="Something"};
return true;
});
其他回答
就像这样:
被嘲笑的方法是
public bool GenerateClient(out Client client);
那么模拟部分将是:
Client client = new Client();
clintMockBll
.Setup(x => x.GenerateClient(out client))
.Returns((Client client1) =>
{
client = new Client(){Name="Something"};
return true;
});
在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);
对克雷格·塞莱斯特的答案进行了增强,任何人都可以使用它。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。
在VS2022中,你可以简单地做:
foo.Setup(e => e.TryGetValue(out It.Ref<ExampleType>.IsAny))
.Returns((ref ExampleType exampleType) => {
exampleType = new ExampleType();
return true;
})
对于“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);
}
我猜当你调用Setup并记住它时,Moq会查看“expectedValue”的值。
作为裁判,我也在寻找答案。
我发现下面的快速入门指南很有用: https://github.com/Moq/moq4/wiki/Quickstart