Mocking RestSharp

2,145 views
Skip to first unread message

prabir

unread,
Nov 3, 2010, 7:03:41 AM11/3/10
to RestSharp
i have been trying to do some mocking with RestClient, RestResponse
and RestRequest with Moq.
unfortunately i could only mock RestClient and couldn't mock
RestResponse and RestRequest.

if these are changed to interface i can mock.

var mockClient = new Mock<RestClient>();
mockClient.Setup(c => c.BaseUrl).Returns("https://
graph.facebook.com");

the above test fails: System.NotSupportedException: Invalid setup on a
non-virtual (overridable in VB) member: c => c.BaseUrl

but if i change to IRestClient use the interface then it works.
var mockClient = new Mock<IRestClient>();
mockClient.Setup(c => c.BaseUrl).Returns("https://
graph.facebook.com");

so to mock the client, i used the interface IRestClient, but
RestResponse and RestRequest doesn't derive from an interface,
so to solve this i create a fake class deriving from RestRequest.

public class FakeRestRequest : RestRequest
{
public new virtual string Resource { get { return
base.Resource; } set { base.Resource = value; } }
}

now when i do

var mockRequest = new Mock<FakeRestRequest>();
mockRequest.Setup(r => r.Resource).Returns("/me");
it works.

from this stack overflow post:
http://stackoverflow.com/questions/1015315/how-do-you-mock-class-with-readonly-property
"The only mocking engine I know of that allows altering non-virtual
methods on classes and sealed classes is Typemock."

which one should be preferable, RestSharp implements the interface
called IRestRequest and IRestResponse or
we should create our own Fake classes like FakeRestRequest?

johnsheehan

unread,
Nov 4, 2010, 5:49:55 PM11/4/10
to RestSharp
I'd be fine if someone contributed IRestRequest and IRestResponse as
long as IHttpRequest and IHttpResponse are done as well.

Stuart Grassie

unread,
Nov 4, 2010, 6:51:01 PM11/4/10
to rest...@googlegroups.com
Because I've had nothing better to do tonight, I've ran Extract Interface on RestRequest, RestResponse and HttpResponse. I can't actually find a class called HttpRequest... there is though a TODO comment in IHttp.cs which seems to be a reminder to move some properties to HttpRequest.

I added the new interfaces as links in the Silverlight project, but not the Windows Phone project.

I've committed the changes up to my fork, but I haven't submitted a pull request: https://github.com/sgrassie/RestSharp/commit/35eeeae96a0257b8488ca3459bb68669cc087c39

It's late here, so if there is a positive response in the morning I'll submit a pull request.

John Sheehan

unread,
Nov 4, 2010, 7:35:29 PM11/4/10
to rest...@googlegroups.com
Oh yeah, I forgot that HttpRequest doesn't exist (and shouldn't). Go
ahead and submit and I'll add the WP links.
Reply all
Reply to author
Forward
0 new messages