2016-07-01 6 views
0

http Web要求と応答メソッドの単体テストを作成したいと思います。私は誰もが上記の方法のためのユニットテストを作成する方法を提案しmethods.Can Web要求のためのユニットテストを書く方法を知らない、http Web要求と応答のユニットテストをC#

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); 
     } 

を以下の方法を見つけてください!

答えて

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

0

あなたは、多くの場合、依存性注入を使用して、インターフェイスではなく、具体的なクラスに依存する必要があります。ホストされたビルドマシンで確実に動作しないサーバーを模擬したくない場合は、模擬HttpWebRequestを作成して注入してください。 NuGetパッケージに興味がない場合は、コードで使用する必要のあるメソッドを含むインターフェイスを作成し、HttpWebRequestを単にラップする実装実装を作成し、単体テスト用の2番目の実装を作成することで、自分で実装できます期待される応答。これにより、サーバーを設定せずにクライアントを単体テストできます。

Here is a SO postMoqで説明しています。

関連する問題