Mock IServiceProvider CreateScope

在用到ISerivceProvider的时候我们通常是需要自己来简独创建一个scope的。 所以在Mock的时候我们也得处理 CreateScope这个方法

using Microsoft.Extensions.DependencyInjection;
using Moq;
using System;

namespace Xunit
{
    public static class ServiceProviderHelper
    {
        public static Mock<IServiceProvider> GetProvider()
        {
            var serviceProvider = new Mock<IServiceProvider>();

            var serviceScope = new Mock<IServiceScope>();
            serviceScope.Setup(x => x.ServiceProvider).Returns(serviceProvider.Object);

            var serviceScopeFactory = new Mock<IServiceScopeFactory>();
            serviceScopeFactory
                .Setup(x => x.CreateScope())
                .Returns(serviceScope.Object);

            serviceProvider
                .Setup(x => x.GetService(typeof(IServiceScopeFactory)))
                .Returns(serviceScopeFactory.Object);

            return serviceProvider;
        }
    }
}

使用它

   var customerService = new Mock<IMalemaCustomerService>();
   var serviceProvider = ServiceProviderHelper.GetProvider();
   serviceProvider.Setup(it => it.GetService(typeof(IMalemaCustomerService))).Returns(customerService.Object);
下一篇:AutoFixture 介绍
最近更新的
...