2014年2月18日 星期二

[C#] Starup IIS express in UnitTest

在寫單元測試的時候,因為有些測試需要先啟動IIS Express的服務(Web api, web service … etc),所以實作了以下程式碼,方便直接在單元測試啟動某個服務。

Example :

[TestMethod]
public void TestStartIisexpress()
{
String siteName = "Icash.Rw.Service";
using(Startup startUp = new Startup())
{
startUp.StartIisexpress(siteName);
}
}


啟動IIS Express的程式碼
/// <summary>
/// 啟動相關服務或程式
/// </summary>
    public class Startup : IDisposable
    {
        private Process _iisProcess;

        /// <summary>
        /// 啟動IIS Express服務
        /// </summary>
        public void StartIisexpress(String siteId)
        {
            try
            {
                var thread = new Thread(new ParameterizedThreadStart(openIisExpress)){ IsBackground = true };
                thread.Start(siteId);
            }
            catch (Exception)
            {
                throw;
            }
        }


        private void openIisExpress(object siteId)
        {
            var startInfo = new ProcessStartInfo
            {
                WindowStyle = ProcessWindowStyle.Normal,
                ErrorDialog = true,
                LoadUserProfile = true,
                CreateNoWindow = false,
                UseShellExecute = false,
                //Arguments = string.Format("/path:\"{0}\" /port:{1}", appLocation, port)
                Arguments = string.Format("/site:{0}", siteId)
            };

            var programfiles = string.IsNullOrEmpty(startInfo.EnvironmentVariables["programfiles"])
                                ? startInfo.EnvironmentVariables["programfiles(x86)"]
                                : startInfo.EnvironmentVariables["programfiles"];

            startInfo.FileName = programfiles + "\\IIS Express\\iisexpress.exe";

            try
            {
                this._iisProcess = new Process { StartInfo = startInfo };

                this._iisProcess.Start();
                this._iisProcess.WaitForExit();
            }
            catch
            {
                this._iisProcess.CloseMainWindow();
                this._iisProcess.Dispose();
            }
        }

        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
           
        }

    }

沒有留言:

張貼留言