【问题标题】:How to inject configuration settings in test classes (ASP.NET Core)?如何在测试类(ASP.NET Core)中注入配置设置?
【发布时间】:2017-07-05 07:00:57
【问题描述】:

SmtpConfig 包含我想在测试类中使用的凭据。 appsettings.development.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "SmtpConfig": {
    "credentials": "username:password"
  }
}

在这里,我将 smtpConfig 配置为注入到类中(在控制器类中工作得很好!) 启动.cs

public IConfigurationRoot Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
      services.AddMvc();

      services.Configure<SmtpConfig(
         Configuration.GetSection(nameof(SmtpConfig)
      ));
}

我想在测试中从 appsettings.development.json 访问凭据,因为在另一台服务器上我会有另一个配置文件。

//important usings
using Microsoft.Extensions.Options;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
    public class SomeControllerAPITest
    {
       private SmtpConfig _smtpConfig;

        public SomeControllerAPITest(IOptions<SmtpConfig> smtpConfig)
        {
            _smtpConfig = smtpConfig.Value;
        }


        [TestMethod]
        public void Post_ReturnsCreatedInstance()
        {
            var credentials = _smtpConfig.credentials;

            //use that credentials
            ...

            //call remote server
            ...
        }
}

有可能吗?

【问题讨论】:

    标签: c# unit-testing testing dependency-injection smtp


    【解决方案1】:

    - 在 testProject 中创建类文件

    public static IConfiguration getConfig(){ 
       var config = new ConfigurationBuilder() 
         .SetBasePath("/Users/Project/")
         .AddJsonFile("appsettings.json")  
         .Build(); 
       return config; 
    }
    

        [TestClass]
        public class TestMasterClass
        {
            public static IConfiguration _configuration { get; set; }
    
            public TestMasterClass()
            {
                _configuration = AnotherClassFile.getConfig();
            }
    
            [TestMethod]
            public void TestConfigElasticSearch()
            {
    
                var elasticSearch = _configuration["ElasticSearchConfig:Link01"];
                Assert.IsNotNull(elasticSearch);
            }
        }
    

    【讨论】:

    • 这个答案可以通过解释你的代码正在做什么来解决所提出的问题来改进。
    【解决方案2】:

    您可以使用相同的Microsoft.Extensions.Configuration 绑定功能来构建相同填充的IOptions&lt;TConfiguration&gt; 实例。以下是我们如何为测试代码实现此功能的大致等价物:

    public class TestSmtpConfigOptions : IOptions<SmtpConfig> {
    
        private static Lazy<SmtpConfig> configuration { get; }
    
        static TestSmtpConfigOptions() {
            configuration = new Lazy<SmtpConfig>(GetConfiguration);
        }
    
        public SmtpConfig Value {
            get { return configuration.Value; }
        }
    
        private static SmtpConfig GetConfiguration() {
            var configuration = new SmtpConfig();
            var path = Path.Combine("config", "appsettings.development.json");
    
            new ConfigurationBuilder()
                .SetBasePath("path/to/base/directory/of/project")
                .AddJsonFile(path, optional: true)
                .Build()
                .GetSection(nameof(SmtpConfig))
                .Bind(configuration);
    
            return configuration;
        }
    
    }
    

    然后,在你的夹具中,你只需要实例化它:

    [TestClass]
    public class SomeControllerAPITest {
    
        private SmtpConfig _smtpConfig;
    
        public SomeControllerAPITest() {
            _smtpConfig = new TestSmtpConfigOptions().Value;
        }
    
    
        [TestMethod]
        public void Post_ReturnsCreatedInstance() {
            var credentials = _smtpConfig.credentials;
    
            //use that credentials
            ...
    
            //call remote server
            ...
        }
    }
    

    如果您关心跨平台路径并且不介意额外的复杂性,这里有一个小类,我们可以使用这个小类以跨平台的方式为我们的 xUnit 测试运行程序获取基本路径。这意味着我们在上面的示例中使用TestConfiguration.BasePath 而不是"path/to/base/directory/of/project"

    internal static class TestConfiguration {
    
        internal static string BasePath { get; }
    
        static TestConfiguration() {
            BasePath = Environment.GetEnvironmentVariable("BASE_DIRECTORY");
    
            if (BasePath == null) {
                BasePath = AppContext.BaseDirectory;
    
                // cross-platform equivalent of "../../../../../"
                for (var index = 0; index < 5; index++) {
                    BasePath = Directory.GetParent(BasePath).FullName;
                }
            }
        }
    
        internal static string ResolvePath(string relativePath) {
            return Path.Combine(BasePath, relativePath);
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      • 1970-01-01
      • 2018-11-05
      • 2022-01-14
      • 1970-01-01
      相关资源
      最近更新 更多