【问题标题】:Unit test for http web request and response in c# [duplicate]c#中http web请求和响应的单元测试[重复]
【发布时间】:2016-11-03 23:54:35
【问题描述】:

我想为 http web 请求和响应方法编写一个单元测试。请找到以下方法,

 public string GetEmployeeId()
        {

                var tokenRequest = (HttpWebRequest)WebRequest.Create("http://www.goggle.com");
                tokenRequest.Method = "POST";
                tokenRequest.ContentType = "application/x-www-form-urlencoded";

                var bytes = Encoding.UTF8.GetBytes(GetKeys(credentials));
                tokenRequest.ContentLength = bytes.Length;

                Response response;
                 using (var stream = tokenRequest.GetRequestStream())
                    {
                        stream.Write(bytes, 0, bytes.Length);
                        stream.Flush();

                        using (var webResponse = request.GetResponse())
                        {
                            Stream receiveStream = webResponse.GetResponseStream();
                            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
                            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(readStream.ReadToEnd()));
                            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Response));
                            response = ser.ReadObject(ms) as Response;
                            ms.Close();
                            readStream.Close();
                        }
                    }
                }
          return response.Id;

        }

  private string GetKeys(Credentials credentials)
        {
            return String.Format(@"client_id={0}&client_secret={1}&grant_type=client_credentials",
                                credentials.Id, credentials.Secret);
        }

我不知道如何为 Web 请求方法编写单元测试。谁能建议如何为上述方法编写单元测试?

【问题讨论】:

    标签: c# unit-testing mocking


    【解决方案1】:

    通过单元测试,您通常必须使用依赖注入并依赖接口而不是具体类。如果您不想模拟在托管构建机器上无论如何都不能可靠运行的服务器,请创建并注入模拟 HttpWebRequest。如果您对 NuGet 包不感兴趣,您可以通过创建一个包含您需要在代码中使用的方法的接口、创建一个简单包装 HttpWebRequest 的生产实现以及为单元测试创​​建第二个实现来简单地分发一个预期的反应。这使您无需设置服务器即可对客户端进行单元测试。

    Here is a SO post 解释了如何使用Moq

    【讨论】:

      【解决方案2】:

      您需要指定要测试的内容。

      您的方法的示例单元测试如下所示:

      [TestClass]
      public class WebUnitTests
      {
         [TestMethod]
         public void Can_Request_Employee_Id()
         {
             // Arrange
             YourHttpRequestClass c = new YourHttpRequestClass();
             var employeeId = c.GetEmployeeId();
      
             // Assert
             Assert.IsFalse(string.IsNullOrEmpty(employeeId));
      
         }
      }
      

      我建议您查看一些单元测试基础知识。

      https://msdn.microsoft.com/en-us/library/hh694602.aspx

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-02
        • 2021-12-19
        • 2018-06-04
        相关资源
        最近更新 更多