我正在尝试对asp.net Core 2.1项目进行一些集成测试。
我在启动文件中初始化了我的连接字符串,但是当我运行测试时,它在处理程序中仍然为空,我的代码出了什么问题?
[TestMethod]
public async Task Method1()
{
var webHostBuilder = new WebHostBuilder()
.UseEnvironment("Development")
.UseStartup<Startup>();
HttpRequestMessage getRequest = new HttpRequestMessage(HttpMethod.Get, "api/action")
{
};
getRequest.Headers.Add("userId", "4622");
getRequest.Headers.Add("clientId", "889");
using (var server = new TestServer(webHostBuilder))
using (var client = server.CreateClient())
{
var result = await client.SendAsync(getRequest);
...
}
}
启动
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
...
services.Configure<SqlConfig>(options =>
{
options.ConnectionString = Configuration.GetConnectionString("DefaultConnection");
});
...
}
SqlConfig
public class SqlConfig
{
public string ConnectionString { get; set; }
}
存储库
public abstract class SqlServerQueryHandler<TQuery, TResult> : BaseQueryHandler<TQuery, TResult>
where TQuery : IQuery<TResult>
{
public SqlServerQueryHandler(IOptions<SqlConfig> connectionString)
{
this.ConnectionString = connectionString.Value.ConnectionString;
}
protected string ConnectionString { get; }
}
答案 0 :(得分:1)
解决我的问题的方法是以下代码:
public class TestStartup : Startup
{
public TestStartup(IConfiguration configuration, IHostingEnvironment env) : base(configuration)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
通过接口在输出目录中包含appsettings.json