简体   繁体   English

单元测试ServiceStack缓存异常

[英]Unit Testing ServiceStack Cache Exception

I'm trying to unit test some ServiceStack services. 我正在尝试对一些ServiceStack服务进行单元测试。 The services use caching. 服务使用缓存。 I can successfully mock my dependencies and, using the MockRequestContext, call my services just fine. 我可以成功模拟我的依赖关系,并使用MockRequestContext调用我的服务就可以了。 But when my services returns it's DTO inside the base.RequestContext.ToOptimizedResultUsingCache, I get a null reference exception from the call below: 但是,当我的服务返回它在base.RequestContext.ToOptimizedResultUsingCache内的DTO时,我从下面的调用中获得空引用异常:

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 调用我的服务方法时,一切看起来都很好,但是当dto保存到此处看到的缓存中时,我得到了空引用异常

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;
                }

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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM