Mocking WebResponse's from a WebRequest

前端 未结 5 913
没有蜡笔的小新
没有蜡笔的小新 2020-12-07 18:43

I have finally started messing around with creating some apps that work with RESTful web interfaces, however, I am concerned that I am hammering their servers every time I h

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-07 19:47

    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."); }

提交回复
热议问题