c#中的http web请求和响应的单元测试

时间:2016-07-01 14:12:07

标签: c# unit-testing mocking

我想为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请求方法编写单元测试。任何人都建议如何为上述方法编写单元测试?

2 个答案:

答案 0 :(得分:0)

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

您的方法的示例单元测试看起来像这样:

[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

答案 1 :(得分:0)

使用单元测试,您经常需要使用依赖注入并依赖接口而不是具体类。如果您不想模拟在托管构建机器上无法可靠运行的服务器,请创建并注入模拟HttpWebRequest。如果您对NuGet包不感兴趣,可以自己创建一个包含需要在代码中使用的方法的接口,创建一个简单包装HttpWebRequest的生产实现,并创建第二个单元测试实现,只需简单地发布预期的回应。这使您可以在不设置服务器的情况下对客户端进行单元测试。

Here is a SO post解释了使用Moq进行的操作。