• Blog
  • Info Support
  • Career
  • Training
  • International Group
  • Info Support
  • Blog
  • Career
  • Training
  • International Group
  • Search
logo InfoSupport
  • Latest blogs
  • Popular blogs
  • Experts
      • All
      • Bloggers
      • Speakers
  • Meet us
  • About us
    • nl
    • en
    • .NET
    • 3D printing
    • Advanced Analytics
    • Agile
    • Akka
    • Alexa
    • Algorithms
    • Api's
    • Architectuur
    • Artificial Intelligence
    • ATDD
    • Augmented Reality
    • AWS
    • Azure
    • Big Data
    • Blockchain
    • Business Intelligence
    • Chatbots
    • Cloud
    • Code Combat
    • Cognitive Services
    • Communicatie
    • Containers
    • Continuous Delivery
    • CQRS
    • Cyber Security
    • Dapr
    • Data
    • Data & Analystics
    • Data Science
    • Data Warehousing
    • Databricks
    • DataOps
    • Developers life
    • DevOps
    • Digital Days
    • Digital Twin
    • Docker
    • eHealth
    • Enterprise Architecture
    • Event Sourcing
    • Hacking
    • Infrastructure & Hosting
    • Innovatie
    • Integration
    • Internet of Things
    • Java
    • Machine Learning
    • Microservices
    • Microsoft
    • Microsoft Bot Framework
    • Microsoft Data Platform
    • Mobile Development
    • Mutation Testing
    • Open source
    • Pepper
    • Power BI
    • Privacy & Ethiek
    • Python
    • Quality Assistance & Test
    • Quality Assurance & Test
    • Requirements Management
    • Scala
    • Scratch
    • Security
    • SharePoint
    • Software Architecture
    • Software development
    • Software Factory
    • SQL Server
    • SSL
    • Start-up
    • Startup thinking
    • Stryker
    • Test Quality
    • Testing
    • TLS
    • TypeScript
    • Various
    • Web Development
    • Web-scale IT
    • Xamarin
    • All
    • Bloggers
    • Speakers
Home » Using the AspNetDevelopmentServer attribute in combination with TeamBuild
  • Using the AspNetDevelopmentServer attribute in combination with TeamBuild

    • By Manuel Riezebosch
    • .NET 12 years ago
    • .NET 0 comments
    • .NET .NET
    Using the AspNetDevelopmentServer attribute in combination with TeamBuild

    Just two statements:

  • Everyone should unit test (or unit integration test, for the purists)
  • Everyone should use TeamBuild (or another nightly build infrastructure)
  • From this we can derive the following statement:

  • Everyone should unit test in combination with TeamBuild!
  •  

    With this in mind I had one little problem regarding the AspNetDevelopmentServer attribute. This attribute allows you to host your web site or service during test execution. The problem I had is that the output directory of the System Under Test (SUT) will be different during the nightly build compared to a local run from Visual Studio. Jim Lamb once wrote an article about it using the solution directory as a base path reference. But this is not a solution for us because we are redirecting the output to a specific directory in the build. But now I found out that it is possible to use the name of the referenced project and MSTest translates this to the location of the published website!

    Consider the following application:

    image

    I have an Implemenation project and an Implementation.Test project where the latter references the first. I slightly modified the default.aspx to print the directory it is running from:

    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = string.Format(CultureInfo.InvariantCulture, "Current folder: {0}.", Server.MapPath(""));
        }
    }

    Then I wrote the following test code:

    [TestClass]
    public class UnitTest1
    {
        public TestContext TestContext { get; set; }
    
        [TestMethod]
        // The first argument is just an identifier that we will use to retrieve the location from the test context.
        // The second argument is the name of the web application project that is referenced.
        [AspNetDevelopmentServer("SomeIdentifier", "Implementation")]
        public void TestMethod1()
        {
            // Retrieve the url of the hosted site from the TestContext and download the page.
            var url = (Uri)TestContext.Properties["AspNetDevelopmentServer.SomeIdentifier"];
            var output = DownloadPage(url);
    
            // Simple check on output.
            StringAssert.Contains(output, "Welcome to ASP.NET!", "Expected welcome string not found in output.");
    
            // Check the current working folder which should be outputed by the page.
            var exp = new Regex(@&quot;Current folder: (?<f>.*).&quot;, RegexOptions.Multiline);
            var match = exp.Match(output);
            Assert.IsTrue(match.Success, &quot;Expected output about current server folder not found.&quot;);
    
            // Write it to the context so we are able to read.
            TestContext.WriteLine(match.Groups[&quot;f&quot;].Value);
        }
    
        /// <summary>
        /// Helper method for download a page from a specific uri.
        /// </summary>
        /// <param name=&quot;uri&quot;>The uri of the page.</param>
        /// <returns>The page content as a string.</returns>
        private static string DownloadPage(Uri uri)
        {
            var request = HttpWebRequest.Create(uri);
    
            using (var response = request.GetResponse())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                return reader.ReadToEnd();
            }
        }
    }

    Remark: Of course a coded UI or web test could be a better alternative for this solution!

    This can of course also be used to host a WCF service in a Web Application and generate a client in the test project to access it. Bill Wang published a blog about redirecting the generated client. I refactored his code somewhat by using extension methods, generics and the EndPointAddressBuilder. Catching exceptions was for me a no-go because I like the details in my test log.

    static class WcfExt
    {
        public static void UrlRedirect<T>(this ClientBase<T> client, Uri uri)
            where T : class
        {
            EndpointAddressBuilder builder = new EndpointAddressBuilder(client.Endpoint.Address);
            builder.Uri = new Uri(client.Endpoint.Address.Uri.OriginalString.Replace(client.Endpoint.Address.Uri.Authority, uri.Authority));
    
            client.Endpoint.Address = builder.ToEndpointAddress();
        }
    }

    Now I can test my service like this:

    [TestMethod]
    [AspNetDevelopmentServer(&quot;SomeIdentifier&quot;, &quot;Implementation&quot;)]
    public void TestMethod2()
    {
        var uri = (Uri)TestContext.Properties[&quot;AspNetDevelopmentServer.SomeIdentifier&quot;];
        var client = new ServiceReference1.Service1Client();
        client.UrlRedirect(uri);
        client.DoWork();
    }

    It is even possible to enable Code Coverage and get results in both a test run from Visual Studio and from the nightly build:

    image

    Share this

Manuel Riezebosch

View profile

Related IT training

Go to training website

Related Consultancy solutions

Go to infosupport.com

Related blogs

  • Building a custom Kubernetes operator in C#

    Building a custom Kubernetes operator in C# Willem Meints - 2 months ago

  • Transform SpecFlow Table Column

    Transform SpecFlow Table Column Ronald Bosma - 5 months ago

  • Building a passwordless login flow with WebAuthn and th…

    Building a passwordless login flow with WebAuthn and th… Willem Meints - 7 months ago

Data Discovery Channel

  • Explainable AI - Break open the blackbox

  • Toekomstvaste microservice data architecturen

  • Modern Data Platform

Nieuwsbrief

* verplichte velden

Contact

  • Head office NL
  • Kruisboog 42
  • 3905 TG Veenendaal
  • T +31 318 552020
  • Call
  • Mail
  • Directions
  • Head office BE
  • Generaal De Wittelaan 17
  • bus 30 2800 Mechelen
  • T +32 15 286370
  • Call
  • Mail
  • Directions

Follow us

  • Twitter
  • Facebook
  • Linkedin
  • Youtube

Newsletter

Sign in

Extra

  • Media Library
  • Disclaimer
  • Algemene voorwaarden
  • ISHBS Webmail
  • Extranet
Beheer cookie toestemming
Deze website maakt gebruik van Functionele en Analytische cookies voor website optimalisatie en statistieken.
Functioneel Always active
De technische opslag of toegang is strikt noodzakelijk voor het legitieme doel het gebruik mogelijk te maken van een specifieke dienst waarom de abonnee of gebruiker uitdrukkelijk heeft gevraagd, of met als enig doel de uitvoering van de transmissie van een communicatie over een elektronisch communicatienetwerk.
Voorkeuren
De technische opslag of toegang is noodzakelijk voor het legitieme doel voorkeuren op te slaan die niet door de abonnee of gebruiker zijn aangevraagd.
Statistieken
De technische opslag of toegang die uitsluitend voor statistische doeleinden wordt gebruikt. De technische opslag of toegang die uitsluitend wordt gebruikt voor anonieme statistische doeleinden. Zonder dagvaarding, vrijwillige naleving door uw Internet Service Provider, of aanvullende gegevens van een derde partij, kan informatie die alleen voor dit doel wordt opgeslagen of opgehaald gewoonlijk niet worden gebruikt om je te identificeren.
Marketing
De technische opslag of toegang is nodig om gebruikersprofielen op te stellen voor het verzenden van reclame, of om de gebruiker op een website of over verschillende websites te volgen voor soortgelijke marketingdoeleinden.
Manage options Manage services Manage vendors Read more about these purposes
Voorkeuren
{title} {title} {title}