如何为Func创建Moq模拟 [英] How do you create a Moq mock for a Func

查看:90
本文介绍了如何为Func创建Moq模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下需要模拟的Func方法

I have the following Func method which i need to mock off

Func<Owned<ISomeInterface>> someMethod { get; set; }

但无法弄清楚如何使用"Moq"框架对其进行模拟.

but cant figure out how to mock it off using 'Moq' framework.

我已经在SO上阅读了类似的帖子,但仍然无法嘲笑它关闭,它总是伴随着

I have read a similar post on SO but still cant seem to mock it off, it always comes back with

表达式不是方法调用:x =>调用(x.someMethod)

Expression is not a method invocation: x => Invoke(x.someMethod )

找不到与给定参数匹配的构造函数 模拟的类型. ----> System.MissingMethodException:构造函数on 找不到类型拥有的1Proxy40a9bf91815d4658ad2453298c903652".

A matching constructor for the given arguments was not found on the mocked type. ----> System.MissingMethodException : Constructor on type 'Owned`1Proxy40a9bf91815d4658ad2453298c903652' not found.

推荐答案

Funct被定义为属性,因此您应在Moq中使用SetupSet.

The Funct is defined as a property so you should use SetupSet within Moq

public interface IPersona
{
    string nome { get; set; }
    string cognome { get; set; }
    Func<Owned<ISomeInterface>> somemethod { get; set; }

}

.在您的测试中:

您为Func创建一个模拟:

You create a mock for the Func:

Func<Owned<ISomeInterface>> somemethodMock = () => new Mock<Owned<ISomeInterface>>().Object; 

然后为包含Func作为属性的Class设置模拟,并在Set方法上设置期望值:

THen you setup the mock for the Class containing the Func as a property and you setup the expectation on the Set method :

var obj = new Mock<IMyInterface>();
obj.SetupSet(x => x.somemethod = somemethodMock).Verifiable();

您为模拟创建容器对象:

You create the container object for the mock:

//We pass the mocked object to the constructor of the container class
var container = new Container(obj.Object);
container.AnotherMethod(somemethodMock);
obj.VerifyAll();

如果将func作为输入参数并将其设置为所包含对象的属性,则这是Container类的Another方法的定义

Here is the definition of Another method of the Container class, if get the func as an input parameter and set it to the property of the contained object

enter  public class Container
{
    private IPersona _persona;

    public Container(IPersona persona)
    {
        _persona = persona;
    }

    public void AnotherMethod(Func<MyClass<IMyInterface>> myFunc)
    {
        _persona.somemethod = myFunc;
    }      
}

这篇关于如何为Func创建Moq模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆