【问题标题】:Unit testing a method with HTTP post request by mocking HttpWebRequest通过模拟 HttpWebRequest 对带有 HTTP 发布请求的方法进行单元测试
【发布时间】:2016-12-16 08:18:07
【问题描述】:

我需要通过 HTTP POST 请求将数据导出为 xml。它是由下面的代码完成的,现在问题是我想通过模拟 http 请求创建单元测试。有人可以帮助我对此进行单元测试吗?

private string WriteBytesToHttp(ExportConfiguration exportConfiguration, byte[] bytes)
    {

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(exportConfiguration.Endpoint.Address);
        Encoding encoding = exportConfiguration.Format.EncodingCodePage.ToEncoding();

        var contentType = string.IsNullOrEmpty(exportConfiguration.Format.ContentType)
            ? "text/plain"
            : exportConfiguration.Format.ContentType;

        request.ContentType = contentType;
        //request.ContentType = string.Format("{0}; charset={1}", contentType, encoding.HeaderName);
        request.ContentLength = bytes.Length;
        request.Method = "POST";

        if (!(string.IsNullOrEmpty(exportConfiguration.Endpoint.Username) ||
            string.IsNullOrEmpty(exportConfiguration.Endpoint.Password)))
        {
            var creditionStr = string.Format("{0}:{1}", exportConfiguration.Endpoint.Username,
                exportConfiguration.Endpoint.Password);

            request.Headers.Add("Authorization",
                "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(creditionStr)));
        }

        Stream newStream = request.GetRequestStream();
        newStream.Write(bytes, 0, bytes.Length);
        newStream.Close();

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream responseStream = response.GetResponseStream();

        var streamReader = string.IsNullOrEmpty(response.CharacterSet)
            ? new StreamReader(responseStream)
            : new StreamReader(responseStream, Encoding.GetEncoding(response.CharacterSet));

        string responseStr = streamReader.ReadToEnd();
        return String.IsNullOrEmpty(responseStr) ? response.StatusCode.ToString() : responseStr;

    }

【问题讨论】:

  • 您的问题究竟是什么?有什么错误吗?
  • 需要通过mock HTTP服务调用为此方法创建unittest
  • 我认为您的问题的答案在这里stackoverflow.com/questions/9789944/…
  • @AmalShalika 这不是问题或问题描述。除了过于复杂的代码(为什么不直接使用 HttpClient?)或使用text/plain 而不是text/xml 等明显的问题,您是否尝试过使用 y 模拟框架?还是抽象接口背后的请求?
  • 您提到了 XML,但您的代码没有引用序列化程序或 XML。您无需使用凭据,而是手动编码授权标头。与其模拟 HttpWebRequest 对象,我更关心代码本身

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


【解决方案1】:

我使用 MockHttpServer 服务来模拟 HttpWebRequest 请求和响应。因此,我将能够对我的代码进行单元测试,而无需创建提取工厂来创建 HttpWebReqeust。下面是使用 MockHttpService 的单元测试代码。

MockHttpService.

Additional References

    [Test]
    public void Http_Transport_ExportPG_Order()
    {
        var port = GetFreeTcpPort();
        var url = string.Format("http://localhost:{0}/api/ifs/import", port);
        ....................

        using (new MockServer(port, "api/ifs/import", (req, rsp, prm) => "Result Body"))
        {
            Wait.For<ExportDispatched>(() =>
                 Bus.Raise(new PutawayPlacedConfirmed(1, 2, 3)), null);
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多