我正在尝试对一些 ServiceStack 服务进行单元测试。服务使用缓存。我可以成功地模拟我的依赖项,并使用 MockRequestContext 调用我的服务就好了。但是当我的服务返回它是 base.RequestContext.ToOptimizedResultUsingCache 内的 DTO 时,我从下面的调用中得到一个空引用异常:
ServiceStack.CacheAccess.Providers.CacheClientExtensions.Cache(ICacheClient cacheClient, String cacheKey, Object responseDto, IRequestContext context, Nullable`1 expireCacheIn)
我的测试设置如下
[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
}
当我调用我的服务方法时,一切看起来都很好,但是当 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;
}