2
votes

I'm trying to unit test a ServiceStack service that uses in memory caching. I'm using the MockRequestContext and when I hit the return base.RequestContext.ToOptimizedResultUsingCache I get an index out of range exception. I'm not sure what's missing. Is it possible to use this mock request context to unit test a service that uses caching?

The Test Code

    [TestMethod]
    public void GetAgencyCase_Returns_AgencyCaseDetailsResponse()
    {
        var service = _container.Resolve<AgencyCaseService>();
        service.SetResolver(new BasicResolver(_container));

        service.RequestContext = new MockRequestContext();

        var response = service.Get(new GetAgencyCase { AgencyId = 2, AgencyCaseNumber = "123" });
    }

And the call to the cache optimize extension method inside the service I'm testing.

return base.RequestContext.ToOptimizedResultUsingCache<AgencyCaseDetailsResponse>(base.Cache, cacheKey, cacheExpireTime, () =>
                {...

Stack Trace from the IndexOutOfRangeException

   at ServiceStack.Common.Web.ContentType.IsBinary(String contentType)
   at ServiceStack.CacheAccess.Providers.CacheClientExtensions.ResolveFromCache(ICacheClient              cacheClient, String cacheKey, IRequestContext context)
   at ServiceStack.ServiceHost.RequestContextExtensions.ToOptimizedResultUsingCache[T](IRequestContext requestContext, ICacheClient cacheClient, String cacheKey, Nullable`1 expireCacheIn, Func`1 factoryFn)
1

1 Answers

3
votes

I figured out the problem. You must provide a response content type with the request in order for the cache call to work. The fix below:

service.RequestContext = new MockRequestContext() { ResponseContentType = ContentType.Json };