Don Fitz
Don Fitz

Reputation: 1174

Unit Testing ServiceStack Cache Exception

I'm trying to unit test some ServiceStack services. The services use caching. I can successfully mock my dependencies and, using the MockRequestContext, call my services just fine. But when my services returns it's DTO inside the base.RequestContext.ToOptimizedResultUsingCache, I get a null reference exception from the call below:

ServiceStack.CacheAccess.Providers.CacheClientExtensions.Cache(ICacheClient cacheClient, String cacheKey, Object responseDto, IRequestContext context, Nullable`1 expireCacheIn)

My test is setup below

[TestMethod]
    public void GetAgencyCase_Returns_AgencyCaseDetailsResponse()
    {
        Container container = new Container();

        Mock<IChangeRequestService> changeRequestService = new Mock<IChangeRequestService>();
        Mock<IRequestService> requestService = new Mock<IRequestService>();

        //Build the case we want returned
        Case testCase = Builder<Case>.CreateNew()
            .With(x => x.CaseId = "123")
            .And(x => x.CaseNumber = "456")
            .With(x => x.Agencies = Builder<CasesAgency>.CreateListOfSize(1)
                .All()
                .With(m => m.Agency = Builder<Agency>.CreateNew().With(z => z.AgencyId = 2).And(z => z.AgencyName = "Test").Build())
                .Build())
            .With(x => x.Requests = Builder<Request>.CreateListOfSize(5)
                .Build())
                .Build();

        requestService.Setup<Case>(x => x.GetCase(It.IsAny<CaseSearchCriteria>(), It.IsAny<AuthenticatedUser>()))
            .Returns(testCase);

        container.Register<IChangeRequestService>(changeRequestService.Object);
        container.Register<IRequestService>(requestService.Object);

        container.Register<ILog>(new Mock<ILog>().Object);
        container.Register<ICacheClient>(new MemoryCacheClient());
        container.RegisterAutoWired<AgencyCaseService>();

        var service = container.Resolve<AgencyCaseService>();
        service.SetResolver(new BasicResolver(container));

        var context = new MockRequestContext() { ResponseContentType = ContentType.Json };
        context.CreateAppHost();

        service.RequestContext = context;


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

Everything looks fine when I call my service method, but I get that null reference exception when the dto is being saved to the cache seen here

try
        {
            var cacheKey = UrnId.Create<GetAgencyCase>(
                request.AgencyId.ToString() +
                request.AgencyCaseNumber);

            var cacheExpireTime = TimeSpan.FromMinutes(_cacheDuration);

            return base.RequestContext.ToOptimizedResultUsingCache<AgencyCaseDetailsResponse>(base.Cache, cacheKey, cacheExpireTime, () =>
                { ...business logic
                  return agencyCaseDto;
                }

Upvotes: 2

Views: 666

Answers (1)

Don Fitz
Don Fitz

Reputation: 1174

Per mythz suggestion in the comments, I added an app host and used its container and the test worked. Below is the updated test.

[TestMethod]
    public void GetAgencyCase_Returns_AgencyCaseDetailsResponse()
    {
        var appHost = new BasicAppHost().Init();//this is needed for caching
        Container container = appHost.Container;

        Mock<IChangeRequestService> changeRequestService = new Mock<IChangeRequestService>();
        Mock<IRequestService> requestService = new Mock<IRequestService>();

        //Build the case we want returned
        Case testCase = Builder<Case>.CreateNew()
            .With(x => x.CaseId = "123")
            .And(x => x.CaseNumber = "456")
            .With(x => x.Agencies = Builder<CasesAgency>.CreateListOfSize(1)
                .All()
                .With(m => m.Agency = Builder<Agency>.CreateNew().With(z => z.AgencyId = 2).And(z => z.AgencyName = "Test").Build())
                .Build())
            .With(x => x.Requests = Builder<Request>.CreateListOfSize(5)
                .Build())
                .Build();

        requestService.Setup<Case>(x => x.GetCase(It.IsAny<CaseSearchCriteria>(), It.IsAny<AuthenticatedUser>()))
            .Returns(testCase);

        container.Register<IChangeRequestService>(changeRequestService.Object);
        container.Register<IRequestService>(requestService.Object);

        container.Register<ILog>(new Mock<ILog>().Object);
        container.Register<ICacheClient>(new MemoryCacheClient());
        container.RegisterAutoWired<AgencyCaseService>();

        var service = container.Resolve<AgencyCaseService>();
        service.SetResolver(new BasicResolver(container));

        var context = new MockRequestContext() { ResponseContentType = ContentType.Json };

        service.RequestContext = context;


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

Upvotes: 1

Related Questions