在这个问题,我发现了一个的这个答案这似乎是解决这个问题对我来说最好的方式。
In this question, I found an this answer that seems to be the best way to solve the problem to me.
所提供的code假定被嘲笑的函数返回一个值:
The provided code assumes that the function that is mocked returns a value:
bool SomeFunc(out ISomeObject o);
不过,我想嘲笑的对象具有了功能如下:
However, the object I want to mock has an out function as follows:
void SomeFunc(out ISomeObject o);
自提答案相关的code片段:
The relevant code fragment from the mentioned answer:
public delegate void OutAction<TOut>(out TOut outVal);
public static IReturnsThrows<TMock, TReturn> OutCallback<TMock, TReturn, TOut>(
this ICallback<TMock, TReturn> mock, OutAction<TOut> action)
where TMock : class
{
// ...
}
太虚不是有效的类型TReturn。因此,我相信我会以某种方式适应这个code让它与方法返回void工作。但如何?
Void is not a valid type for TReturn. So I believe I would have to somehow adapt this code to get it to work with methods returning void. But how?
也许你只需要这样的:
ISomeObject so = new SomeObject(...);
yourMock.Setup(x => x.SomeFunc(out so));
然后,当你使用 yourMock.Object
在code在测试中,所以
实例将神奇的问世为退出
参数。
Then when you use yourMock.Object
in the code you test, the so
instance will "magically" come out as the out
parameter.
这是一个有点非直观的(出来是),但它的工作原理。
It is a little non-intuitive ("out is in"), but it works.
增加:不知道我理解的情景。下面完整的程序工作正常:
Addition: Not sure I understand the scenario. The following complete program works fine:
static class Program
{
static void Main()
{
// test the instance method from 'TestObject', passing in a mock as 'mftbt' argument
var testObj = new TestObject();
var myMock = new Mock<IMyFaceToBeTested>();
IMyArgFace magicalOut = new MyClass();
myMock.Setup(x => x.MyMethod(out magicalOut)).Returns(true);
testObj.TestMe(myMock.Object);
}
}
class TestObject
{
internal void TestMe(IMyFaceToBeTested mftbt)
{
Console.WriteLine("Now code to be tested is running. Calling the method");
IMyArgFace maf; // not assigned here, out parameter
bool result = mftbt.MyMethod(out maf);
Console.WriteLine("Method call completed");
Console.WriteLine("Return value was: " + result);
if (maf == null)
{
Console.WriteLine("out parameter was set to null");
}
else
{
Console.WriteLine("out parameter non-null; has runtime type: " + maf.GetType());
}
}
}
public interface IMyFaceToBeTested
{
bool MyMethod(out IMyArgFace maf);
}
public interface IMyArgFace
{
}
class MyClass : IMyArgFace
{
}
请说明你的情况怎么样不同的是,使用的类和接口的名字从我的例子。
Please indicate how your situation is different, by using the names of the classes and interfaces from my example.