Unit testing an HttpApplication

后端 未结 3 1964
天涯浪人
天涯浪人 2020-12-31 10:45

I have a class derived from HttpApplication that adds some extra features. I\'m to the point where I need to unit test these features, which means I have to be able to creat

3条回答
  •  清酒与你
    2020-12-31 11:14

    I found the following blog earlier which explains quite a nice approach using Microsoft Moles.

    http://maraboustork.co.uk/index.php/2011/03/mocking-httpwebresponse-with-moles/

    In short the solution suggests the following:

        [TestMethod]
        [HostType("Moles")]
        [Description("Tests that the default scraper returns the correct result")]
        public void Scrape_KnownUrl_ReturnsExpectedValue()
        {
            var mockedWebResponse = new MHttpWebResponse();
    
            MHttpWebRequest.AllInstances.GetResponse = (x) =>
            {
                return mockedWebResponse;
            };
    
            mockedWebResponse.StatusCodeGet = () => { return HttpStatusCode.OK; };
            mockedWebResponse.ResponseUriGet = () => { return new Uri("http://www.google.co.uk/someRedirect.aspx"); };
            mockedWebResponse.ContentTypeGet = () => { return "testHttpResponse"; }; 
    
            var mockedResponse = " \r\n" +
                                 "   \r\n" +
                                 "   \r\n" +
                                 "     

    Hello World

    \r\n" + " \r\n" + ""; var s = new MemoryStream(); var sw = new StreamWriter(s); sw.Write(mockedResponse); sw.Flush(); s.Seek(0, SeekOrigin.Begin); mockedWebResponse.GetResponseStream = () => s; var scraper = new DefaultScraper(); var retVal = scraper.Scrape("http://www.google.co.uk"); Assert.AreEqual(mockedResponse, retVal.Content, "Should have returned the test html response"); Assert.AreEqual("http://www.google.co.uk/someRedirect.aspx", retVal.FinalUrl, "The finalUrl does not correctly represent the redirection that took place."); }

提交回复
热议问题