如何在测试类中注入配置设置(ASP.NET Core)?

Ale*_*lex 6 c# testing unit-testing dependency-injection smtp

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

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "SmtpConfig": {
    "credentials": "username:password"
  }
}
Run Code Online (Sandbox Code Playgroud)

在这里我配置要在类中注入的smtpConfig(在控制器类中工作得非常好!)Startup.cs

public IConfigurationRoot Configuration { get; }

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

      services.Configure<SmtpConfig(
         Configuration.GetSection(nameof(SmtpConfig)
      ));
}
Run Code Online (Sandbox Code Playgroud)

我想在测试中从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
            ...
        }
}
Run Code Online (Sandbox Code Playgroud)

有可能吗?

Tec*_*ium 0

您可以使用相同的Microsoft.Extensions.Configuration绑定功能来构建填充相同的IOptions<TConfiguration>实例。以下是我们在测试代码中实现此方法的大致等效方式:

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

然后,在你的装置中,你只需要实例化它:

[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
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您关心跨平台路径并且不介意一点额外的复杂性,这里有一个小类,我们使用它以跨平台方式为 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);
    }

}
Run Code Online (Sandbox Code Playgroud)