我正在尝试获取一个MVC6应用程序进行自我托管以进行测试。我可以使用TestServer进行内存中测试,但是为了测试多个Web应用程序的集成,其中一个包含一个我无法控制的中间件,该中间件无法连接到另一个应用程序,因此我至少需要一个应用程序才能通过TCP。
我尝试使用WebApp.Start
,但是它与IAppBuilder
而不是一起使用IApplicationBuilder
,因此无法使其与Startup一起使用。
是否有任何方法可以通过OWIN或其他任何方式使MVC6应用程序在xUnit测试中进行自我托管?
更新:
FWIW,基于Pinpoint的答案和一些其他研究,至少在测试与MVC项目位于同一项目中时,我能够提出以下在xUnit中工作的基类:
public class WebTestBase : IDisposable
{
private IDisposable webHost;
public WebTestBase()
{
var env = CallContextServiceLocator.Locator.ServiceProvider.GetRequiredService<IApplicationEnvironment>();
var builder = new ConfigurationBuilder(env.ApplicationBasePath)
.AddIniFile("hosting.ini");
var config = builder.Build();
webHost = new WebHostBuilder(CallContextServiceLocator.Locator.ServiceProvider, config)
.UseEnvironment("Development")
.UseServer("Microsoft.AspNet.Server.WebListener")
.Build()
.Start();
}
public void Dispose()
{
webHost.Dispose();
}
}
Katana的WebApp
静态类已被替换为WebHostBuilder
,该类提供了更为灵活的方法:https : //github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting/WebHostBuilder.cs。
您可能已经在没有意识到的情况下使用了此API,因为当您在project.json(例如Microsoft.AspNet.Hosting server=Microsoft.AspNet.Server.WebListener server.urls=http://localhost:54540
)中注册新的Web命令并使用dnx
(例如dnx . web
)运行它时,它是托管块使用的组件:
namespace Microsoft.AspNet.Hosting
{
public class Program
{
private const string HostingIniFile = "Microsoft.AspNet.Hosting.ini";
private const string ConfigFileKey = "config";
private readonly IServiceProvider _serviceProvider;
public Program(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public void Main(string[] args)
{
// Allow the location of the ini file to be specified via a --config command line arg
var tempBuilder = new ConfigurationBuilder().AddCommandLine(args);
var tempConfig = tempBuilder.Build();
var configFilePath = tempConfig[ConfigFileKey] ?? HostingIniFile;
var appBasePath = _serviceProvider.GetRequiredService<IApplicationEnvironment>().ApplicationBasePath;
var builder = new ConfigurationBuilder(appBasePath);
builder.AddIniFile(configFilePath, optional: true);
builder.AddEnvironmentVariables();
builder.AddCommandLine(args);
var config = builder.Build();
var host = new WebHostBuilder(_serviceProvider, config).Build();
using (host.Start())
{
Console.WriteLine("Started");
var appShutdownService = host.ApplicationServices.GetRequiredService<IApplicationShutdown>();
Console.CancelKeyPress += (sender, eventArgs) =>
{
appShutdownService.RequestShutdown();
// Don't terminate the process immediately, wait for the Main thread to exit gracefully.
eventArgs.Cancel = true;
};
appShutdownService.ShutdownRequested.WaitHandle.WaitOne();
}
}
}
}
https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting/Program.cs
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句