Robin Robin - 3 months ago 25
C# Question

In ServiceStack is it possible to mock the Request.OriginalRequest object for unit tests?

I'd like to make my ServiceStack service testable.

Presently I have:

[RequireFormsAuthentication]
public object Delete(DeleteRequest request)
{
var originalRequest = (HttpRequest)Request.OriginalRequest;
var identity = originalRequest.RequestContext.HttpContext.User.Identity;
return othercode(identity);
}


Where RequireFormsAuthentication is

public class RequireFormsAuthenticationAttribute : RequestFilterAttribute
{
public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
{
var originalRequest = (HttpRequest)req.OriginalRequest;
var identity = originalRequest.RequestContext.HttpContext.User.Identity;
if (!identity.IsAuthenticated)
{
res.StatusCode = (int)HttpStatusCode.Forbidden;
res.EndServiceStackRequest(skipHeaders: true);
}
}
}


I've mocked out all the dependencies used by 'othercode()' and all that's left is the stuff that's in the base class Service. Is there a pattern/strategy/approach/something I'm missing that makes this trivial?

Answer

I apologize for not using moq...already had some of this done using RhinoMocks. I think the concept should transfer to moq. This might be a good resource as well as this this.

Anyway, I think the test code below should get you started. Your seam into mocking Request.OriginalRequest is replaceing the Service.RequestContext with a mock object. Then you just have to mock everything beyond that. It's going to be a lot of 'mocking' and if you repeat to yourself 'Are you mocking me' every time you mock a class it's almost enjoyable.

[Test]
public void testsomethign()
{
    var mockedRequestContext = MockRepository.GenerateMock<IRequestContext>();
    var mockedHttpRequest = MockRepository.GenerateMock<IHttpRequest>();
    var mockedOriginalRequest = MockRepository.GenerateMock<HttpRequestBase>();
    var mockedOriginalRequestContext = MockRepository.GenerateMock<RequestContext>();

    mockedOriginalRequest.Stub(x => x.RequestContext).Return(mockedOriginalRequestContext);
    mockedHttpRequest.Stub(x => x.OriginalRequest).Return(mockedOriginalRequest);

    mockedRequestContext.Stub(x => x.Get<IHttpRequest>()).Return(mockedHttpRequest);
    var service = new ServiceTests()
    {
        RequestContext = mockedRequestContext
    };

    service.Delete(new DeleteRequest());
}
Comments