Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a method that returns dynamic return type with Moq

Tags:

c#

mocking

moq

Given the following interface:

public interface IApiHelper
{
   dynamic CallApi(string url);
}

I've delclared an instantiated a Mock<IApiHelper> _apiHelperMock

I'm trying to write a test that returns a Success = true property, to mimic a JSON result. My setup looks like this:

_apiHelperMock.Setup(o => o.CallApi(It.IsAny<string>())).Returns((dynamic)new { Success = true });

However I get the following error when trying to run the test: Moq.Language.Flow.ISetup' does not contain a definition for 'Returns'

Can anyone tell me what I'm doing wrong here?

like image 668
Marcus K Avatar asked Dec 23 '15 21:12

Marcus K


2 Answers

I was able to create an ExpandoObject and cast it to object.

dynamic userInfo = new ExpandoObject();
dynamic user1 = new ExpandoObject();
user1.title = "aaa";
dynamic user2 = new ExpandoObject();
user2.title = "bbb";
userInfo.groups = new List<ExpandoObject> { user1 , user2 };

var endpointMock = new Mock<IRestEndpointHandler>();
endpointMock.Setup(c => c.RequestJsonDynamicGet(It.IsAny<Uri>())).Returns((object)userInfo);
like image 144
Czechdude Avatar answered Nov 17 '22 08:11

Czechdude


You don't have to cast the anonymous type object to dynamic.

Try this:

_apiHelperMock
    .Setup(o => o.CallApi(It.IsAny<string>()))
    .Returns(new { Success = true });
like image 3
Yacoub Massad Avatar answered Nov 17 '22 07:11

Yacoub Massad