Ihab Kharrosheh
Ihab Kharrosheh

Reputation: 21

Mock method that returns Task<dynamic>

I have unit test for a method that returns dynamic and when I try to setup and returns a dynamic value it gets an error on running the test saying

The best overloaded method match for 'Moq.etc' has some invalid arguments

_managerMock.Setup(x => x.someMethod(It.IsAny<int>()))
            .Returns(Task.FromResult(resource));

Upvotes: 1

Views: 933

Answers (1)

Peter Csala
Peter Csala

Reputation: 22679

You have two options:

With var

If your resource variable is not declared as dynamic then you don't need anything special. All you need is the good old ReturnsAsync. (Please prefer ReturnsAsync over Returns with Task.FromResult)

var resource = new {Id = 1};
_managerMock.Setup(mgr => mgr.SomeMethod(It.IsAny<int>()))
    .ReturnsAsync(resource);

In this sample I've created an anonymous type but you can use whatever you want.

With dynamic

If you declare your resource as dynamic then you need to use another overload of the ReturnsAsync. Instead of specifying the return value you need to specify the valueFunction.

dynamic resource = new {Id = 1};
_managerMock.Setup(mgr => mgr.SomeMethod(It.IsAny<int>()))
    .ReturnsAsync(() => resource);

In this sample I've created an anonymous lambda but you can use whatever you want.

Upvotes: 1

Related Questions