ASP.NET MVC 5 Hosting for Integration / E2E Testing
public static class ApplicationUtilities
{
private static Process _webHostProcess;
private const string WEB_APP_NAME = "BookShop.Web";
private const int WEB_APP_PORT = 12345;
public static void StartApplication()
{
var webHostStartInfo = GetProcessStartInfo();
_webHostProcess = Process.Start(webHostStartInfo);
_webHostProcess.TieLifecycleToParentProcess();
}
public static void StopApplication()
{
if (_webHostProcess == null)
return;
if (!_webHostProcess.HasExited)
_webHostProcess.Kill();
_webHostProcess.Dispose();
}
public static string ApplicationBaseUrl
{
get { return string.Format("http://localhost:{0}", WEB_APP_PORT); }
}
public static string GetFullUrl(string relativePath)
{
return string.Format("{0}{1}", ApplicationUtilities.ApplicationBaseUrl, relativePath);
}
private static string GetSolutionFolderPath()
{
var directory = new DirectoryInfo(Environment.CurrentDirectory);
while (directory.GetFiles("*.sln").Length == 0)
{
directory = directory.Parent;
}
return directory.FullName;
}
private static ProcessStartInfo GetProcessStartInfo()
{
var key = Environment.Is64BitOperatingSystem ? "programfiles(x86)" : "programfiles";
var programfiles = Environment.GetEnvironmentVariable(key);
var startInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Normal,
ErrorDialog = true,
LoadUserProfile = true,
CreateNoWindow = false,
UseShellExecute = false,
Arguments = String.Format("/path:\"{0}\" /port:{1}", Path.Combine(GetSolutionFolderPath(), @"src\" + WEB_APP_NAME), WEB_APP_PORT),
FileName = string.Format("{0}\\IIS Express\\iisexpress.exe", programfiles)
};
// Add any environment variables
// startInfo.EnvironmentVariables.Add(key, value);
return startInfo;
}
}