How do you create a Moq mock for a Func

2019-07-06 03:32发布

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.

标签: c# mocking moq
1条回答
看我几分像从前
2楼-- · 2019-07-06 03:45

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;
    }      
}
查看更多
登录 后发表回答