我有以下 Func 方法,我需要模拟它
Func<Owned<ISomeInterface>> someMethod { get; set; }
但无法弄清楚如何使用“Moq”框架来模拟它。
我读过类似的post https://stackoverflow.com/questions/6036708/how-to-moq-a-func就这样,但似乎仍然无法嘲笑它,它总是回来
表达式不是方法调用: x => Invoke(x.someMethod )
or
在上找不到给定参数的匹配构造函数
嘲笑类型。 ----> System.MissingMethodException:构造函数
找不到类型“Owned`1Proxy40a9bf91815d4658ad2453298c903652”。
Funct 被定义为一个属性,因此您应该在 Moq 中使用 SetupSet
public interface IPersona
{
string nome { get; set; }
string cognome { get; set; }
Func<Owned<ISomeInterface>> somemethod { get; set; }
}
。在你的测试中:
您为 Func 创建一个模拟:
Func<Owned<ISomeInterface>> somemethodMock = () => new Mock<Owned<ISomeInterface>>().Object;
然后,您为包含 Func 作为属性的类设置模拟,并设置对 Set 方法的期望:
var obj = new Mock<IMyInterface>();
obj.SetupSet(x => x.somemethod = somemethodMock).Verifiable();
您为模拟创建容器对象:
//We pass the mocked object to the constructor of the container class
var container = new Container(obj.Object);
container.AnotherMethod(somemethodMock);
obj.VerifyAll();
这是Container类的另一个方法的定义,如果获取func作为输入参数并将其设置为所包含对象的属性
enter public class Container
{
private IPersona _persona;
public Container(IPersona persona)
{
_persona = persona;
}
public void AnotherMethod(Func<MyClass<IMyInterface>> myFunc)
{
_persona.somemethod = myFunc;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)