簡體   English   中英

NUnit與ASP.NET網站

[英]NUnit with an ASP.NET web site

我正在嘗試升級我們的構建服務器,從沒有構建服務器到擁有一個!

我正在使用JetBrains的TeamCity (使用ReSharper幾年,我相信他們的東西),並打算使用NUnitMSBuild

但是,我提出了一個問題:似乎無法使用NUnit測試ASP.NET網站。 我曾經假設可以在構建之后將其配置為測試App_Code,但似乎很好地進行測試的唯一方法是將網站轉換為Web應用程序(我的老板不喜歡這個想法)。

我怎么能這樣做?

請記住,測試需要能夠從TeamCity自動觸發。

  • 如果您想對您的網站進行冒煙測試,或者在某些端點上進行測試 - 請參閱下面的代碼。

  • 另一方面,如果您想測試不可測試(可偽造的)ASP.NET網站程序集(而不是Web應用程序),那么就像他們在法國所說的那樣,SOL

程序集是一個隨機命名的動態編譯程序集,深入框架臨時ASP.NET文件的大小,使得測試幾乎不可能。

你真的需要考慮幾個選擇:

  1. 將需要測試的邏輯放在單獨的程序集中。
  2. 更改為提供可測試程序集的Web應用程序項目。

對不起,我不認為你會找到你想要的,但我可能是錯的。 讓我們來看看。

祝好運


下載帶有站點和應用程序的Visual Studio 2008示例

我為WebHost.WebServer.dll編寫了一個包裝器,它是開發服務器的核心,在CI中運行良好。 我用它所有的時間。

這是一個縮小版本,包括一個用法示例。

test.cs中

using System.Net;
using NUnit.Framework;

namespace Salient.Excerpts
{
    [TestFixture]
    public class WebHostServerFixture : WebHostServer
    {
        [TestFixtureSetUp]
        public void TestFixtureSetUp()
        {
            // debug/bin/testproject/solution/siteundertest - make sense?
            StartServer(@"..\..\..\..\TestSite");

            // is the equivalent of
            // StartServer(@"..\..\..\..\TestSite",
            // GetAvailablePort(8000, 10000, IPAddress.Loopback, true), "/", "localhost");
        }
        [TestFixtureTearDown]
        public void TestFixtureTearDown()
        {
            StopServer();
        }

        [Test]
        public void Test()
        {
            // while a reference to the web app under test is not necessary,
            // if you do add a reference to this test project you may F5 debug your tests.
            // if you debug this test you will break in Default.aspx.cs
            string html = new WebClient().DownloadString(NormalizeUri("Default.aspx"));
        }
    }
}

WebHostServer.cs

// Project: Salient
// http://salient.codeplex.com
// Date: April 16 2010

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
using Microsoft.VisualStudio.WebHost;

namespace Salient.Excerpts
{
    /// <summary>
    /// A general purpose Microsoft.VisualStudio.WebHost.Server test fixture.
    /// WebHost.Server is the core of the Visual Studio Development Server (WebDev.WebServer).
    ///
    /// This server is run in-process and may be used in F5 debugging.
    /// </summary>
    /// <remarks>
    /// If you are adding this source code to a new project, You will need to
    /// manually add a reference to WebDev.WebHost.dll to your project. It cannot
    /// be added from within Visual Studio.
    ///
    /// Please see the Readme.txt accompanying this code for details.
    /// </remarks>
    /// NOTE: code from various namespaces/classes in the Salient project have been merged into this
    /// single class for this post in the interest of brevity
    public class WebHostServer
    {
        private Server _server;

        public string ApplicationPath { get; private set; }

        public string HostName { get; private set; }

        public int Port { get; private set; }

        public string VirtualPath { get; private set; }

        public string RootUrl
        {
            get { return string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}{2}", HostName, Port, VirtualPath); }
        }

        /// <summary>
        /// Combine the RootUrl of the running web application with the relative url specified.
        /// </summary>
        public virtual Uri NormalizeUri(string relativeUrl)
        {
            return new Uri(RootUrl + relativeUrl);
        }

        /// <summary>
        /// Will start "localhost" on first available port in the range 8000-10000 with vpath "/"
        /// </summary>
        /// <param name="applicationPath"></param>
        public void StartServer(string applicationPath)
        {
            StartServer(applicationPath, GetAvailablePort(8000, 10000, IPAddress.Loopback, true), "/", "localhost");
        }

        /// <summary>
        /// </summary>
        /// <param name="applicationPath">Physical path to application.</param>
        /// <param name="port">Port to listen on.</param>
        /// <param name="virtualPath">Optional. defaults to "/"</param>
        /// <param name="hostName">Optional. Is used to construct RootUrl. Defaults to "localhost"</param>
        public void StartServer(string applicationPath, int port, string virtualPath, string hostName)
        {
            if (_server != null)
            {
                throw new InvalidOperationException("Server already started");
            }

            // WebHost.Server will not run on any other IP
            IPAddress ipAddress = IPAddress.Loopback;

            if(!IsPortAvailable(ipAddress, port))
            {
                throw new Exception(string.Format("Port {0} is in use.", port));
            }

            applicationPath = Path.GetFullPath(applicationPath);

            virtualPath = String.Format("/{0}/", (virtualPath ?? string.Empty).Trim('/')).Replace("//", "/");

            _server = new Server(port, virtualPath, applicationPath, false, false);
            _server.Start();

            ApplicationPath = applicationPath;
            Port = port;
            VirtualPath = virtualPath;
            HostName = string.IsNullOrEmpty(hostName) ? "localhost" : hostName;
        }

        /// <summary>
        /// Stops the server.
        /// </summary>
        public void StopServer()
        {
            if (_server != null)
            {
                _server.Stop();
                _server = null;
                // allow some time to release the port
                Thread.Sleep(100);
            }
        }

        public void Dispose()
        {
            StopServer();
        }


       /// <summary>
        /// Gently polls specified IP:Port to determine if it is available.
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <param name="port"></param>
        public static bool IsPortAvailable(IPAddress ipAddress, int port)
        {
            bool portAvailable = false;

            for (int i = 0; i < 5; i++)
            {
                portAvailable = GetAvailablePort(port, port, ipAddress, true) == port;
                if (portAvailable)
                {
                    break;
                }
                // be a little patient and wait for the port if necessary,
                // the previous occupant may have just vacated
                Thread.Sleep(100);
            }
            return portAvailable;
        }

        /// <summary>
        /// Returns first available port on the specified IP address.
        /// The port scan excludes ports that are open on ANY loopback adapter.
        ///
        /// If the address upon which a port is requested is an 'ANY' address all
        /// ports that are open on ANY IP are excluded.
        /// </summary>
        /// <param name="rangeStart"></param>
        /// <param name="rangeEnd"></param>
        /// <param name="ip">The IP address upon which to search for available port.</param>
        /// <param name="includeIdlePorts">If true includes ports in TIME_WAIT state in results.
        /// TIME_WAIT state is typically cool down period for recently released ports.</param>
        /// <returns></returns>
        public static int GetAvailablePort(int rangeStart, int rangeEnd, IPAddress ip, bool includeIdlePorts)
        {
            IPGlobalProperties ipProps = IPGlobalProperties.GetIPGlobalProperties();

            // if the ip we want a port on is an 'any' or loopback port we need to exclude all ports that are active on any IP
            Func<IPAddress, bool> isIpAnyOrLoopBack = i => IPAddress.Any.Equals(i) ||
                                                           IPAddress.IPv6Any.Equals(i) ||
                                                           IPAddress.Loopback.Equals(i) ||
                                                           IPAddress.IPv6Loopback.
                                                               Equals(i);
            // get all active ports on specified IP.
            List<ushort> excludedPorts = new List<ushort>();

            // if a port is open on an 'any' or 'loopback' interface then include it in the excludedPorts
            excludedPorts.AddRange(from n in ipProps.GetActiveTcpConnections()
                                   where
                                       n.LocalEndPoint.Port >= rangeStart &&
                                       n.LocalEndPoint.Port <= rangeEnd && (
                                       isIpAnyOrLoopBack(ip) || n.LocalEndPoint.Address.Equals(ip) ||
                                        isIpAnyOrLoopBack(n.LocalEndPoint.Address)) &&
                                        (!includeIdlePorts || n.State != TcpState.TimeWait)
                                   select (ushort)n.LocalEndPoint.Port);

            excludedPorts.AddRange(from n in ipProps.GetActiveTcpListeners()
                                   where n.Port >= rangeStart && n.Port <= rangeEnd && (
                                   isIpAnyOrLoopBack(ip) || n.Address.Equals(ip) || isIpAnyOrLoopBack(n.Address))
                                   select (ushort)n.Port);

            excludedPorts.AddRange(from n in ipProps.GetActiveUdpListeners()
                                   where n.Port >= rangeStart && n.Port <= rangeEnd && (
                                   isIpAnyOrLoopBack(ip) || n.Address.Equals(ip) || isIpAnyOrLoopBack(n.Address))
                                   select (ushort)n.Port);

            excludedPorts.Sort();

            for (int port = rangeStart; port <= rangeEnd; port++)
            {
                if (!excludedPorts.Contains((ushort)port))
                {
                    return port;
                }
            }

            return 0;
        }
    }
}

注意: Microsoft.VisualStudio.WebHost命名空間包含在WebDev.WebHost.dll文件中。 此文件位於GAC中,但無法在Visual Studio中添加對此程序集的引用。

要添加引用,您需要在文本編輯器中打開.csproj文件並手動添加引用。

查找包含項目引用的ItemGroup並添加以下元素:

<Reference Include="WebDev.WebHost, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=x86">
  <Private>False</Private>
</Reference>

參考: http//www.codeproject.com/KB/aspnet/test-with-vs-devserver-2.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM