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;
}
}
:
[TestClass]
public class SomeControllerAPITest {
private SmtpConfig _smtpConfig;
public SomeControllerAPITest() {
_smtpConfig = new TestSmtpConfigOptions().Value;
}
[TestMethod]
public void Post_ReturnsCreatedInstance() {
var credentials = _smtpConfig.credentials;
...
...
}
}
, , , - 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;
for (var index = 0; index < 5; index++) {
BasePath = Directory.GetParent(BasePath).FullName;
}
}
}
internal static string ResolvePath(string relativePath) {
return Path.Combine(BasePath, relativePath);
}
}