是否可以模拟.NET HttpWebResponse?

时间:2012-03-22 13:16:10

标签: c# .net unit-testing mocking moq

我有一个集成测试,可以从第三方服务器获取一些json结果。它非常简单,效果很好。

我希望停止实际点击此服务器并使用Moq(或任何Mocking库,如ninject等)来劫持并强制返回结果。

这可能吗?

以下是一些示例代码: -

public Foo GoGetSomeJsonForMePleaseKThxBai()
{
    // prep stuff ...

    // Now get json please.
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("Http://some.fancypants.site/api/hiThere);
    httpWebRequest.Method = WebRequestMethods.Http.Get;

    string responseText;

    using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
    {
        using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
        {
            json = streamReader.ReadToEnd().ToLowerInvariant();
        }
    }

    // Check the value of the json... etc..
}

当然,这个方法是从我的测试中调用的。

我在想,也许我需要传递给这个方法(或类的一个属性?)一个模拟的httpWebResponse或者其他东西,但是不太确定是不是这样。此外,响应是httpWebRequest.GetResponse()方法的输出..所以也许我只需要传入一个模拟的HttpWebRequest?。

任何带有示例代码的建议都会得到最多的肯定!

7 个答案:

答案 0 :(得分:65)

您可能希望更改您的消费代码,以获取工厂的接口,该工厂创建可以模拟的请求和响应,以包装实际的实现。

更新:重新访问

在我的回答被接受之后很久我就得到了投票,我承认我原来的答案质量很差,做了一个很大的假设。

在4.5 +

中模拟HttpWebRequest

我原来答案的混淆在于你可以在4.5中模拟HttpWebResponse,但不能在早期版本中模拟[Test] public void Create_should_create_request_and_respond_with_stream() { // arrange var expected = "response content"; var expectedBytes = Encoding.UTF8.GetBytes(expected); var responseStream = new MemoryStream(); responseStream.Write(expectedBytes, 0, expectedBytes.Length); responseStream.Seek(0, SeekOrigin.Begin); var response = new Mock<HttpWebResponse>(); response.Setup(c => c.GetResponseStream()).Returns(responseStream); var request = new Mock<HttpWebRequest>(); request.Setup(c => c.GetResponse()).Returns(response.Object); var factory = new Mock<IHttpWebRequestFactory>(); factory.Setup(c => c.Create(It.IsAny<string>())) .Returns(request.Object); // act var actualRequest = factory.Object.Create("http://www.google.com"); actualRequest.Method = WebRequestMethods.Http.Get; string actual; using (var httpWebResponse = (HttpWebResponse)actualRequest.GetResponse()) { using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream())) { actual = streamReader.ReadToEnd(); } } // assert actual.Should().Be(expected); } public interface IHttpWebRequestFactory { HttpWebRequest Create(string uri); } 。在4.5中模拟它也使用过时的构造函数。因此,建议的行动方案是抽象请求和响应。无论如何,下面是使用.NET 4.5和Moq 4.2的完整工作测试。

[Test]
public void Create_should_create_request_and_respond_with_stream()
{
    // arrange
    var expected = "response content";
    var expectedBytes = Encoding.UTF8.GetBytes(expected);
    var responseStream = new MemoryStream();
    responseStream.Write(expectedBytes, 0, expectedBytes.Length);
    responseStream.Seek(0, SeekOrigin.Begin);

    var response = new Mock<IHttpWebResponse>();
    response.Setup(c => c.GetResponseStream()).Returns(responseStream);

    var request = new Mock<IHttpWebRequest>();
    request.Setup(c => c.GetResponse()).Returns(response.Object);

    var factory = new Mock<IHttpWebRequestFactory>();
    factory.Setup(c => c.Create(It.IsAny<string>()))
        .Returns(request.Object);

    // act
    var actualRequest = factory.Object.Create("http://www.google.com");
    actualRequest.Method = WebRequestMethods.Http.Get;

    string actual;

    using (var httpWebResponse = actualRequest.GetResponse())
    {
        using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
        {
            actual = streamReader.ReadToEnd();
        }
    }


    // assert
    actual.Should().Be(expected);
}

public interface IHttpWebRequest
{
    // expose the members you need
    string Method { get; set; }

    IHttpWebResponse GetResponse();
}

public interface IHttpWebResponse : IDisposable
{
    // expose the members you need
    Stream GetResponseStream();
}

public interface IHttpWebRequestFactory
{
    IHttpWebRequest Create(string uri);
}

// barebones implementation

private class HttpWebRequestFactory : IHttpWebRequestFactory
{
    public IHttpWebRequest Create(string uri)
    {
        return new WrapHttpWebRequest((HttpWebRequest)WebRequest.Create(uri));
    }
}

public class WrapHttpWebRequest : IHttpWebRequest
{
    private readonly HttpWebRequest _request;

    public WrapHttpWebRequest(HttpWebRequest request)
    {
        _request = request;
    }

    public string Method
    {
        get { return _request.Method; }
        set { _request.Method = value; }
    }

    public IHttpWebResponse GetResponse()
    {
        return new WrapHttpWebResponse((HttpWebResponse)_request.GetResponse());
    }
}

public class WrapHttpWebResponse : IHttpWebResponse
{
    private WebResponse _response;

    public WrapHttpWebResponse(HttpWebResponse response)
    {
        _response = response;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (_response != null)
            {
                ((IDisposable)_response).Dispose();
                _response = null;
            }
        }
    }

    public Stream GetResponseStream()
    {
        return _response.GetResponseStream();
    }
}

更好的答案:摘要响应和请求

这是一个更安全的抽象实现抽象,适用于以前的版本(好吧,至少降至3.5):

{{1}}

答案 1 :(得分:8)

答案 2 :(得分:5)

我不会嘲笑HttpWebResponse,而是将调用包装在接口后面,并模拟该接口。

如果您正在测试Web响应是否也访问了我想要的网站,那么这与A类调用WebResponse接口以获取所需数据的测试不同。

对于模拟界面,我更喜欢Rhino mocks。请参阅here了解如何使用它。

答案 3 :(得分:3)

如果有帮助,请使用NSubstitute代替Moq在下面找到接受答案中说明的代码

using NSubstitute; /*+ other assemblies*/

[TestMethod]
public void Create_should_create_request_and_respond_with_stream()
{
   //Arrange
   var expected = "response content";
   var expectedBytes = Encoding.UTF8.GetBytes(expected);
   var responseStream = new MemoryStream();
   responseStream.Write(expectedBytes, 0, expectedBytes.Length);
   responseStream.Seek(0, SeekOrigin.Begin);

   var response = Substitute.For<HttpWebResponse>();
   response.GetResponseStream().Returns(responseStream);

   var request = Substitute.For<HttpWebRequest>();
   request.GetResponse().Returns(response);

   var factory = Substitute.For<IHttpWebRequestFactory>();
   factory.Create(Arg.Any<string>()).Returns(request);

   //Act
   var actualRequest = factory.Create("http://www.google.com");
   actualRequest.Method = WebRequestMethods.Http.Get;

   string actual;

   using (var httpWebResponse = (HttpWebResponse)actualRequest.GetResponse())
   {
       using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
       {
           actual = streamReader.ReadToEnd();
       }
   }

   //Assert
   Assert.AreEqual(expected, actual);
}

public interface IHttpWebRequestFactory
{
    HttpWebRequest Create(string uri);
}

单元测试运行并成功通过。

对我已经找了一段时间如何有效地做到这一点的答案进行了投票。

答案 4 :(得分:2)

Microsoft的HTTP堆栈都没有考虑到单元测试和分离而开发。

您有三种选择:

  • 尽可能减少对网络的调用(即发送和获取数据并传递给其他方法)并测试其余方法。就网络电话而言,那里应该有很多神奇的事情并且非常简单。
  • 将HTTP调用包装在另一个类中,并在测试时传递模拟对象。
  • 用其他两个类包装HttpWebResponseHttpWebRequest。这就是MVC团队对HttpContext所做的工作。

第二个选项:

interface IWebCaller
{
    string CallWeb(string address);
}

答案 5 :(得分:1)

您实际上可以在不嘲笑的情况下返回HttpWebResponse,请参阅我的回答here。它不需要任何“外部”代理接口,只需要“标准”WebRequest WebResponseICreateWebRequest

如果您不需要访问HttpWebResponse并且只能处理WebResponse,那就更容易了;我们在单元测试中这样做,以返回“预制”内容响应以供消费。我必须“加倍努力”才能返回实际的HTTP状态代码,以模拟例如404响应要求您使用HttpWebResponse,以便访问StatusCode属性等

假设所有内容为HttpWebXXX 的其他解决方案忽略WebRequest.Create()支持的除HTTP 之外的所有内容,它可以是您关注的任何已注册前缀的处理程序(通过{{如果您忽略了这一点,那么您就错过了,因为它是一种很好的方式来公开您无法访问的其他内容流,例如Embeeded Resource Streams,File stream等。

此外,明确地将WebRequest.RegisterPrefix()的回复转换为WebRequest.Create() 是破坏的途径,因为方法返回类型为HttpWebRequest并再次显示一些不了解API的实际运作方式。

答案 6 :(得分:-1)

我在blog post找到了一个很好的解决方案:

使用非常简单,只需要这样做:

string response = "my response string here";
WebRequest.RegisterPrefix("test", new TestWebRequestCreate());
TestWebRequest request = TestWebRequestCreate.CreateTestRequest(response);

将这些文件复制到您的项目中:

    class TestWebRequestCreate : IWebRequestCreate
{
    static WebRequest nextRequest;
    static object lockObject = new object();

    static public WebRequest NextRequest
    {
        get { return nextRequest ;}
        set
        {
            lock (lockObject)
            {
                nextRequest = value;
            }
        }
    }

    /// <summary>See <see cref="IWebRequestCreate.Create"/>.</summary>
    public WebRequest Create(Uri uri)
    {
        return nextRequest;
    }

    /// <summary>Utility method for creating a TestWebRequest and setting
    /// it to be the next WebRequest to use.</summary>
    /// <param name="response">The response the TestWebRequest will return.</param>
    public static TestWebRequest CreateTestRequest(string response)
    {
        TestWebRequest request = new TestWebRequest(response);
        NextRequest = request;
        return request;
    }
}

class TestWebRequest : WebRequest
{
    MemoryStream requestStream = new MemoryStream();
    MemoryStream responseStream;

    public override string Method { get; set; }
    public override string ContentType { get; set; }
    public override long ContentLength { get; set; }

    /// <summary>Initializes a new instance of <see cref="TestWebRequest"/>
    /// with the response to return.</summary>
    public TestWebRequest(string response)
    {
        responseStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(response));
    }

    /// <summary>Returns the request contents as a string.</summary>
    public string ContentAsString()
    {
        return System.Text.Encoding.UTF8.GetString(requestStream.ToArray());
    }

    /// <summary>See <see cref="WebRequest.GetRequestStream"/>.</summary>
    public override Stream GetRequestStream()
    {
        return requestStream;
    }

    /// <summary>See <see cref="WebRequest.GetResponse"/>.</summary>
    public override WebResponse GetResponse()
    {
        return new TestWebReponse(responseStream);
    }
}

class TestWebReponse : WebResponse
{
    Stream responseStream;

    /// <summary>Initializes a new instance of <see cref="TestWebReponse"/>
    /// with the response stream to return.</summary>
    public TestWebReponse(Stream responseStream)
    {
        this.responseStream = responseStream;
    }

    /// <summary>See <see cref="WebResponse.GetResponseStream"/>.</summary>
    public override Stream GetResponseStream()
    {
        return responseStream;
    }
}