与IOptions的集成测试.NET Core中 [英] Integration test with IOptions<> in .NET Core

查看:121
本文介绍了与IOptions的集成测试.NET Core中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将IOption<T>传递给我的CommandBus,以便可以从我的ServiceBusSetting类中获取设置.我想对总线进行集成测试.我不想解决它,只需使用new QueueCommandBus并需要将IOptions传递给它.

I pass IOption<T> to my CommandBus so I can get the settings from my ServiceBusSetting class. I want to do an integration test of my Bus. I do not want to resolve it just use new QueueCommandBus and need to pass IOptions to it.

var services = new ServiceCollection().AddOptions();
        services.Configure<ServiceBusAppSettings>(Configuration.GetSection("ServiceBus"));
        var options = services.BuildServiceProvider().GetService<IOptions<ServiceBusAppSettings>>();

        ////Act
        var commandBus = new QueueCommandBus(options);

这很好用,但是感觉很复杂,需要从测试项目中的appsetting.json中获取IOptions<T>的代码.

This works fine, but feels very complex code to get the IOptions<T> from my appsetting.json in my test project.

任何提示,如果这是唯一的方法还是有更好的方法?

Any clue if this is the only way or is there a better way?

推荐答案

您无需创建ServiceCollectionIServiceProvider. IConfiguration接口具有Bind()方法,或者从.NET Core 1.1开始,是Get<T>,您可以使用该方法直接获取强类型对象:

You don't need to create the ServiceCollection or IServiceProvider. The IConfiguration interface has a Bind() method, or from .NET Core 1.1 onwards, Get<T> which you can use to get the strongly-typed object directly:

var config = Configuration.GetSection("ServiceBus");

// .NET Core 1.0
var options = new ServiceBusAppSettings();
config.Bind(options);

// .NET Core 1.1
var options = config.Get<ServiceBusAppSettings>();

我喜欢将这些作为静态方法添加到我的AppSettings强类型对象中,以方便在Web应用程序和单元测试中从JSON加载它们.

I like to add these as static methods to my AppSettings strongly-typed object, to make it convenient to load them from JSON in both my web app and from unit tests.

AppSettings.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

namespace My.Namespace
{
    public class AppSettings
    {
        public class ServiceBusAppSettings
        {
            public string Setting1;
            public int Setting2;
        }

        public class ApiSettings
        {
            public bool FormatJson { get; set; }
        }

        public class MySqlSettings
        {
            public string User { get; set; }
            public string Password { get; set; }
            public string Host { get; set; }
            public string Database { get; set; }
            public int Port { get; set; } = 3306;

            public string GetConnectionString()
            {
                return $"Server={Host};Database={Database};Port={Port};Uid={User};Pwd={Password}";
            }

        }

        public ServiceBusAppSettings ServiceBus { get; set; } = new ServiceBusAppSettings();
        public ApiSettings Api { get; set; } = new ApiSettings();
        public MySqlSettings MySql { get; set; } = new MySqlSettings();

        // Static load helper methods. These could also be moved to a factory class.
        public static IConfigurationRoot GetConfiguration(string dir)
        {
            return GetConfiguration(dir, null);
        }

        public static IConfigurationRoot GetConfiguration(string dir, string environmentName)
        {
            if (string.IsNullOrEmpty(environmentName))
                environmentName = "Development";

            var builder = new ConfigurationBuilder()
                .SetBasePath(dir)
                .AddJsonFile("appsettings.json", true, true)
                .AddJsonFile($"appsettings.{environmentName}.json", true)
                .AddEnvironmentVariables();

            return builder.Build();
        }

        public static AppSettings GetSettings(string dir)
        {
            return GetSettings(dir, null);
        }

        public static AppSettings GetSettings(string dir, string environmentName)
        {
            var config = GetConfiguration(dir, environmentName);
            return GetSettings(config);
        }

        public static AppSettings GetSettings(IConfiguration config)
        {
            return config.Get<AppSettings>();
        }
    }
}

ASP.NET Core Startup.cs:(在配置其他服务时,在此阶段获取强类型设置对象通常很有帮助...)

ASP.NET Core Startup.cs: (Getting the strongly-typed settings object is often helpful at this stage, when configuring the other services...)

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        Configuration = AppSettings.GetConfiguration(env.ContentRootPath, env.EnvironmentName);
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Configure the service collection.
        services.AddOptions();
        services.Configure<AppSettings>(Configuration);

        // It can also be handy to get the AppSettings object here.
        var settings = AppSettings.GetSettings(Configuration);

        // Add framework services.
        services.AddMvc()
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                // Pretty-print JSON in Development
                options.SerializerSettings.Formatting = settings.Api.FormatJson ? Formatting.Indented : Formatting.None;
            });

        // Store DB connection info in AppSettings too...
        var conn = settings.MySql.GetConnectionString();
        services.AddDbContext<MyDbContext>(opt => opt.UseMySql(conn));
    }
}

在测试课中:

var testDir = AppContext.BaseDirectory;
var settings = AppSettings.GetSettings(testDir, "Test");

//Act
var commandBus = new QueueCommandBus(settings);

这篇关于与IOptions的集成测试.NET Core中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆