Web Services 模拟来自WebRequest的WebResponse

zengzsys  于 2022-11-15  发布在  其他
关注(0)|答案(6)|浏览(108)

我终于开始在创建一些使用RESTful Web界面的应用程序方面做得一团糟,但是,我担心每次我点击F5来运行一系列测试时,我都会锤击他们的服务器。
基本上,我需要得到一系列的Web响应,这样我就可以测试我是否正确地解析了不同的响应,而不是每次都命中他们的服务器,我想我可以这样做一次,保存XML,然后在本地工作。
但是,我不知道如何“模拟”WebResponse,因为(AFAIK)它们只能由WebRequest.GetResponse示例化
你们是怎么嘲笑这种事情的?是吗?我只是真的不喜欢我攻击他们的服务器的事实:我不想改变代码 * 太 * 多,但我希望有一个优雅的方式来做这件事。

接受后更新

威尔的回答是我需要的一记耳光,我知道我错过了一个基本点!

  • 创建一个将返回表示XML的代理对象的接口。
  • 实现该接口两次,一次使用WebRequest,另一次返回静态“响应”。
  • 然后,接口实现基于响应或静态XML示例化返回类型。
  • 然后,您可以在测试或生产时将所需的类传递给服务层。

一旦我有了代码,我会粘贴一些样本。

k3fezbri

k3fezbri1#

我发现这个问题,而寻找做完全相同的事情。找不到答案的任何地方,但经过多一点挖掘发现,.Net框架已内置支持这一点。
你可以用WebRequest.RegisterPrefix注册一个工厂对象,当WebRequest.Create使用那个前缀(或url)时,WebRequest.Create会调用它。工厂对象必须实现IWebRequestCreate,它有一个Create方法,返回一个WebRequest。这里你可以返回你的模拟WebRequest
我在http://blog.salamandersoft.co.uk/index.php/2009/10/how-to-mock-httpwebrequest-when-unit-testing/上放了一些示例代码

qmb5sa22

qmb5sa222#

下面是一个不需要模拟的解决方案,您可以实现WebRequest的所有三个组件:IWebRequestCreateWebRequestWebResponse。请看下面。我的示例生成失败的请求(通过抛出WebException),但应该能够使其发送“真实的的”响应:

class WebRequestFailedCreate : IWebRequestCreate {
    HttpStatusCode status;
    String statusDescription;
    public WebRequestFailedCreate(HttpStatusCode hsc, String sd) {
        status = hsc;
        statusDescription = sd;
    }
    #region IWebRequestCreate Members
    public WebRequest Create(Uri uri) {
        return new WebRequestFailed(uri, status, statusDescription);
    }
    #endregion
}
class WebRequestFailed : WebRequest {
    HttpStatusCode status;
    String statusDescription;
    Uri itemUri;
    public WebRequestFailed(Uri uri, HttpStatusCode status, String statusDescription) {
        this.itemUri = uri;
        this.status = status;
        this.statusDescription = statusDescription;
    }
    WebException GetException() {
        SerializationInfo si = new SerializationInfo(typeof(HttpWebResponse), new System.Runtime.Serialization.FormatterConverter());
        StreamingContext sc = new StreamingContext();
        WebHeaderCollection headers = new WebHeaderCollection();
        si.AddValue("m_HttpResponseHeaders", headers);
        si.AddValue("m_Uri", itemUri);
        si.AddValue("m_Certificate", null);
        si.AddValue("m_Version", HttpVersion.Version11);
        si.AddValue("m_StatusCode", status);
        si.AddValue("m_ContentLength", 0);
        si.AddValue("m_Verb", "GET");
        si.AddValue("m_StatusDescription", statusDescription);
        si.AddValue("m_MediaType", null);
        WebResponseFailed wr = new WebResponseFailed(si, sc);
        Exception inner = new Exception(statusDescription);
        return new WebException("This request failed", inner, WebExceptionStatus.ProtocolError, wr);
    }
    public override WebResponse GetResponse() {
        throw GetException();
    }
    public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) {
        Task<WebResponse> f = Task<WebResponse>.Factory.StartNew (
            _ =>
            {
                throw GetException();
            },
            state
        );
        if (callback != null) f.ContinueWith((res) => callback(f));
        return f;
    }
    public override WebResponse EndGetResponse(IAsyncResult asyncResult) {
        return ((Task<WebResponse>)asyncResult).Result;
    }

}
class WebResponseFailed : HttpWebResponse {
    public WebResponseFailed(SerializationInfo serializationInfo, StreamingContext streamingContext)
        : base(serializationInfo, streamingContext) {
    }
}

您必须创建HttpWebResponse子类,因为您无法以其他方式创建子类。
枣手的部分(在GetException()方法中)是输入你不能覆盖的值,例如StatusCode,这是我们最好的伙伴SerializaionInfo的用武之地!这是你提供你不能覆盖的值的地方。显然,覆盖你能覆盖的部分(HttpWebResponse),以获得剩下的方法。
我是如何获得所有那些AddValue()调用中的“名称”的?从异常消息中!依次告诉我每一个都很好,直到我让它高兴为止。
现在,编译器会抱怨“过时”,但这仍然有效,包括.NET Framework版本4。
以下是一个(通过)测试用例,供参考:

[TestMethod, ExpectedException(typeof(WebException))]
    public void WebRequestFailedThrowsWebException() {
        string TestURIProtocol = TestContext.TestName;
        var ResourcesBaseURL = TestURIProtocol + "://resources/";
        var ContainerBaseURL = ResourcesBaseURL + "container" + "/";
        WebRequest.RegisterPrefix(TestURIProtocol, new WebRequestFailedCreate(HttpStatusCode.InternalServerError, "This request failed on purpose."));
        WebRequest wr = WebRequest.Create(ContainerBaseURL);
        try {
            WebResponse wrsp = wr.GetResponse();
            using (wrsp) {
                Assert.Fail("WebRequest.GetResponse() Should not have succeeded.");
            }
        }
        catch (WebException we) {
            Assert.IsInstanceOfType(we.Response, typeof(HttpWebResponse));
            Assert.AreEqual(HttpStatusCode.InternalServerError, (we.Response as HttpWebResponse).StatusCode, "Status Code failed");
            throw we;
        }
    }
mpgws1up

mpgws1up3#

你不能。最好的办法是把它 Package 在一个代理对象中,然后模仿它。或者,你必须使用一个模仿框架,它可以拦截不能被模仿的类型,比如TypeMock。但是你在这里谈论的是巴克斯。最好做一点 Package 。
显然你可以做一些额外的工作。在这里检查投票最高的答案。

cotxawn7

cotxawn74#

我发现下面的博客早些时候解释了一个相当不错的方法使用微软摩尔。
http://maraboustork.co.uk/index.php/2011/03/mocking-httpwebresponse-with-moles/
简而言之,解决方案建议如下:

[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 = "<html> \r\n" +
                             "  <head></head> \r\n" +
                             "  <body> \r\n" +
                             "     <h1>Hello World</h1> \r\n" +
                             "  </body> \r\n" +
                             "</html>";

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

aij0ehis5#

这不是一个完美的解决方案,但它以前对我很有效,值得特别注意的是它的简单性:
HTTPSimulator
还有一个在typemock forums中记录的typemock示例:

using System;
using System.IO;
using System.Net;
using NUnit.Framework;
using TypeMock;

namespace MockHttpWebRequest
{
  public class LibraryClass
  {
    public string GetGoogleHomePage()
    {
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
      HttpWebResponse response = (HttpWebResponse)request.GetResponse();
      using (StreamReader reader = new StreamReader(response.GetResponseStream()))
      {
        return reader.ReadToEnd();
      }
    }
  }

  [TestFixture]
  [VerifyMocks]
  public class UnitTests
  {
    private Stream responseStream = null;
    private const string ExpectedResponseContent = "Content from mocked response.";

    [SetUp]
    public void SetUp()
    {
      System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
      byte[] contentAsBytes = encoding.GetBytes(ExpectedResponseContent);
      this.responseStream = new MemoryStream();
      this.responseStream.Write(contentAsBytes, 0, contentAsBytes.Length);
      this.responseStream.Position = 0;
    }

    [TearDown]
    public void TearDown()
    {
      if (responseStream != null)
      {
        responseStream.Dispose();
        responseStream = null;
      }
    }

    [Test(Description = "Mocks a web request using natural mocks.")]
    public void NaturalMocks()
    {
      HttpWebRequest mockRequest = RecorderManager.CreateMockedObject<HttpWebRequest>(Constructor.Mocked);
      HttpWebResponse mockResponse = RecorderManager.CreateMockedObject<HttpWebResponse>(Constructor.Mocked);
      using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
        WebRequest.Create("http://www.google.com");
        recorder.CheckArguments();
        recorder.Return(mockRequest);

        mockRequest.GetResponse();
        recorder.Return(mockResponse);

        mockResponse.GetResponseStream();
        recorder.Return(this.responseStream);
      }

      LibraryClass testObject = new LibraryClass();
      string result = testObject.GetGoogleHomePage();
      Assert.AreEqual(ExpectedResponseContent, result);
    }

    [Test(Description = "Mocks a web request using reflective mocks.")]
    public void ReflectiveMocks()
    {
      Mock<HttpWebRequest> mockRequest = MockManager.Mock<HttpWebRequest>(Constructor.Mocked);
      MockObject<HttpWebResponse> mockResponse = MockManager.MockObject<HttpWebResponse>(Constructor.Mocked);
      mockResponse.ExpectAndReturn("GetResponseStream", this.responseStream);
      mockRequest.ExpectAndReturn("GetResponse", mockResponse.Object);

      LibraryClass testObject = new LibraryClass();
      string result = testObject.GetGoogleHomePage();
      Assert.AreEqual(ExpectedResponseContent, result);
    }
  }
}
xcitsw88

xcitsw886#

您可以使用NSubstitute,例如

var httpWebResponse = Substitute.For<HttpWebResponse>();
        httpWebResponse.StatusCode.Returns(HttpStatusCode.NotFound);
        httpWebResponse.StatusDescription.Returns("Not Found");

相关问题