2017-10-17 129 views
1

我想用Moq來測試這個方法。有人能告訴我如何做到這一點? 我在查詢字符串中附加了用戶標識和值。如何在moq中模仿這個。該類的名稱是RestClient.cs。我創建了一個名爲IRestClient的接口。 公共接口IRestClient { 串makeRequest的(字符串userid,字符串值); }使用Moq框架進行單元測試

這是RESTClient實現類的makeRequest的方法

public string MakeRequest(string userId,string value) 
{ 
    Logger.Info("Entering method MakeRequest()." + "Input Parameter: " + userId+Constant.NewLine+value); 
    string strResponseValue = string.Empty; 

    // The HttpWebRequest class allows you to programatically make web requests against an HTTP server. 
    // create the WebRequest instantiated for making the request to the specified URI. 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Constant.webServerURI+"?id="+userId + Constant.UserValueAppend + value); 

    //Gets or sets the method for the request.(Overrides WebRequest.Method.) 
    request.Method = httpMethod.ToString(); 

    //Initially response from webserver is set to null. 
    HttpWebResponse response = null; 

    try 
    { 
     // Get the response in the response object of type HttpWebResponse 
     // The request object of HttpWebRequest class is used to "get" the response (GetResponse()) from WebServer and store it in the response object 
     response = (HttpWebResponse)request.GetResponse(); 

     // We check that the response StatusCode is good and we can proceed 
     if (response.StatusCode != HttpStatusCode.OK) 
     { 
      Logger.Error("Error" + response.StatusCode.ToString()); 
      throw new ApplicationException(Constant.ErrorDisplay + response.StatusCode.ToString()); 
     } 

     // Process the response string 
     // We obtain the ResponseStream from the webserver using "get" (GetResponseStream()) 
     // The Stream Class provides a generic view of a sequence of bytes 

     using (Stream responseStream = response.GetResponseStream()) 
     { 
      if (responseStream != null) 
      { 
       using (StreamReader reader = new StreamReader(responseStream)) 
       { 
        //read the stream and store it in string strResponseValue 
        strResponseValue = reader.ReadToEnd(); 

        }//End of StreamReader 
      } 
     }//End of using ResponseStream 
    }// End of using Response 

    catch (Exception ex) 
    { 
     Logger.Error("Error" + ex.Message.ToString()); 
     strResponseValue = ("Error " + ex.Message.ToString()); 
    } 
    finally 
    { 
     if (response != null) 
     { 
      ((IDisposable)response).Dispose(); 
     } 
    } 
    //return the string strResponseValue 
    Logger.Info("Leaving method MakeRequest." + "Output parameter: " + strResponseValue); 
    return strResponseValue; 
} 

這是我在創造我的單元測試類的最小起訂量稱爲RestClientTests.cs

嘗試
[TestMethod] 
public void TestMethod1() 
{ 
    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 mockRestClient = new Mock<IRestClient>(); 
    var mockHttpRequest = new Mock<HttpWebRequest>(); 

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

    mockHttpRequest.Setup(c => c.GetResponse()).Returns(response.Object); 

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

    var actualRequest = factory.Object.Create("http://localhost:8080"); 
    actualRequest.Method = WebRequestMethods.Http.Get; 

    string actual; 

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

    mockRestClient.Setup(moq => moq.MakeRequest("xxx", "s")).Returns(actual); 
} 

我IhttpWebRequestFactory界面看起來像這個:

interface IHttpWebRequestFactory 
{ 
    HttpWebRequest Create(string uri); 

} 

我是牛逼知道如何測試這個

回答

0

您當前的測試方法是沒有意義的我。

如果您正在測試您的RestClient類,它實現IRestClient,則不需要模擬IRestClient本身。你需要嘲笑所有的外部依賴關係 - 你已經創建了模擬IHttpWebRequestFactory,現在你需要將它注入到測試對象中。我沒有看到你的班級的其餘部分,但我認爲你的WebRequest對象是IHttpWebRequestFactory類型 - 你需要指定你的工廠模擬。

現在你需要定義測試用例。我可以很快看到以下內容(但您可以有更多原因):

  1. StatusCode不正確。
  2. StatusCode可以,但是responseStream爲null。
  3. StatusCode正常,responseStream不爲null,方法執行成功。
  4. 在try塊中拋出異常。

現在對於每個測試用例,你需要準備適當的設置和驗證。例如,對於第一次,您需要您的模擬工廠返回模擬請求,該請求將返回模擬響應而不是OK結果代碼。現在你需要調用你的實際對象。作爲驗證,您需要檢查是否拋出了ApplicationException,並且實際調用了所有的嘲笑。

好的,這是第二測試案例的部分設置。這將準備嘲笑工廠返回嘲笑請求,它會返回OK代碼嘲笑迴應:

var response = new Mock<HttpWebResponse>(); 
response.SetupGet(c => c.StatusCode).Returns(HttpStatusCode.OK); 

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

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

你能提供什麼,你只是通過代碼表示的例子..都說狀態代碼是確定 –

+0

我試圖測試在Restclient類 –

+1

中的makeRequest方法非常感謝@arghtype –

相關問題