将IServiceCollection暴露给测试注册的最佳方法?

时间:2018-12-18 17:37:38

标签: c# unit-testing asp.net-core nunit

我正在更新一些我已经使用了一段时间的旧的autofac代码,以测试ioc注册;使其与aspnetcore中的MS内置IOC容器一起使用。一些较新的api内置在aspnetcore中,并且不使用autofac。

下面是我正在玩的沙箱:

namespace GatewayProxy.Tests
{
    [TestFixture]
    public class Tests : GivenTheNetCoreService<ITestReg>
    {
        private TestServer _server;
        private HttpClient _client;

        protected override void GivenThat()
        {
            _server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
            _client = _server.CreateClient();
            base.GivenThat();
        }

        [Test]
        public void Test1()
        {
            Result.Should().BeOfType<TestReg>();
        }
    }

    [TestFixture]
    public abstract class GivenTheNetCoreService<T> where T : class
    {
        private ServiceCollection _serviceCollection;
        public T Result { get; private set; }

        [OneTimeSetUp]
        public void Setup()
        {
            GivenThat();

            When();
        }

        protected virtual void GivenThat()
        {
            _serviceCollection = new ServiceCollection();
        }

        protected virtual void When()
        {
            using (var serviceProvider = _serviceCollection.BuildServiceProvider().CreateScope())
            {
                Result = serviceProvider.ServiceProvider.GetRequiredService<T>();
            }
        }
    }
}

在我的startup.cs中,我有:

private void IocRegistrations(IServiceCollection services)
{
    services.AddTransient<ITestReg, TestReg>();
}

Result属性为null,因为其中ServiceProvider没有任何“已实现的服务”。那么,最好的方法是测试ITestReg是否已正确注册?

1 个答案:

答案 0 :(得分:0)

您可以通过server.Host.Services访问服务。

using Microsoft.Extensions.DependencyInjection;

var server = new TestServer(
                WebHost.CreateDefaultBuilder()
                        .UseStartup<Startup>()
    );
var testReg = server.Host.Services.GetRequiredService<ITestReg>();
var test = testReg.HelloWorld();