从模拟方法返回模拟 [英] Return a Mock from a Mocked method
问题描述
我不确定该怎么做.
鉴于我有
public interface IFactory<T> where T : new()
{
IWrapper<T> GetT(string s);
}
public interface IWrapper<out T> where T : new()
{
void Execute(Action<T> action);
}
当我这样做
public class MoqTest
{
public void test()
{
Mock<IWrapper<basicClass>> wrapperMock = new Mock<IWrapper<basicClass>>();
Mock<IFactory<basicClass>> factoryMock = new Mock<IFactory<basicClass>>()
.Setup(p => p.GetT(It.IsAny<string>()))
.Returns(wrapperMock.Object);
}
}
我明白了
无法隐式转换类型
Moq.Language.Flow.IReturnsResult<TestNamespace.IFactory<TestNamespace.basicClass>>
到Moq.Mock<TestNamespace.IFactory<TestNamespace.basicClass>>
.一个 存在显式转换(您是否缺少演员表?)
Cannot implicitly convert type
Moq.Language.Flow.IReturnsResult<TestNamespace.IFactory<TestNamespace.basicClass>>
toMoq.Mock<TestNamespace.IFactory<TestNamespace.basicClass>>
. An explicit conversion exists (are you missing a cast?)
请注意,这些只是模拟的示例对象.
Note that these are just mocked example objects.
似乎不认为返回类型等效.一个是IReturnResult
,另一个是Moq.Mock
It seems it doesn't consider the return type equivalent. One being a IReturnResult
, the other a Moq.Mock
推荐答案
您的问题基本上是,您将调用Returns
方法的结果分配给factoryMock
变量.
Your problem basically is that you are assigning the result of invoking the Returns
method to the factoryMock
variable.
您要先创建模拟并将其分配给factoryMock
变量,然后按如下所示设置模拟:
You want to first create the mock and assign it to the factoryMock
variable and then set the mock up like this:
Mock<IWrapper<basicClass>> wrapperMock = new Mock<IWrapper<basicClass>>();
Mock<IFactory<basicClass>> factoryMock = new Mock<IFactory<basicClass>>();
factoryMock
.Setup(p => p.GetT(It.IsAny<string>()))
.Returns(wrapperMock.Object);
这篇关于从模拟方法返回模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!