6

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?

Ry-
  • 218,210
  • 55
  • 464
  • 476
Robin
  • 698
  • 6
  • 25

3 Answers3

7

Here's how to test with Moq. This service looks for a "key" and "value" in the query string and another parameter in the request DTO. The service returns a string response based on the value given.

    [Test]
    public void MyTest()
    {
        var mockRequestContext = new Mock<IRequestContext>();
        var mockedHttpRequest = new Mock<IHttpRequest>();

        NameValueCollection querystring = new NameValueCollection();
        querystring.Add("myKey", "myValue");

        mockedHttpRequest.SetupGet(r => r.QueryString).Returns(querystring);

        mockRequestContext.Setup(x => x.Get<IHttpRequest>()).Returns(mockedHttpRequest.Object);

        AboutService service = new AboutService
        {
            RequestContext  = mockRequestContext.Object,
        };

        AboutResponse response = (AboutResponse)service.Any(new About
        {
            Company = "myOtherValue",
        });

        Assert.AreEqual(0, response.QueryResult);
        Assert.AreEqual("validResponse", response.Version);
    }
northben
  • 5,448
  • 4
  • 35
  • 47
3

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());
}
Community
  • 1
  • 1
paaschpa
  • 4,816
  • 11
  • 15
  • That covers quite a lot, actually. Thanks! One more thing, however: do you know how I can override the protected member 'Request'? (line 4 in my first code block will fail with NRE) – Robin Apr 26 '13 at 10:22
  • Also... it seems 'HttpRequest' is a sealed class and can't be mocked. – Robin Apr 26 '13 at 11:54
  • Yeah, HttpReqeust is sealed I think you can cast to HttpRequestBase instead? Line 12 (mockedRequestContext.Stub(x => x.Get()).Return(mockedHttpRequest)) Should allow you to mock the Request member. – paaschpa Apr 26 '13 at 16:51
2

Be sure to check out the namespace: ServiceStack.ServiceInterface.Testing.
In there you can find a MockRequestContext that you can use as follows:

var mockContext = new ServiceStack.ServiceInterface.Testing.MockRequestContext();
//do stuff to set it up if desired...

AboutService service = new AboutService
{
    RequestContext  = mockContext
};
Wes
  • 1,059
  • 13
  • 18