How do you create a Moq mock for a Func

六月ゝ 毕业季﹏ 提交于 2019-12-14 01:39:59

问题


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

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

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

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

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

or

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


回答1:


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; }

}

. In your test :

You create a mock for the Func:

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

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();

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;
    }      
}


来源:https://stackoverflow.com/questions/8755726/how-do-you-create-a-moq-mock-for-a-func

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!