2015-11-24 59 views
2

我想寫一個單元測試,其中我的sut(authMock)的依賴項應該拋出帶有特定響應的Webexception(json將相應地在該sut中解析)。不過我有麻煩投擲使用起訂量一樣,在引發WebException:嘲笑Webexception包括Web響應

Stream responseStream = null; 
using (var stringstream = @"{""errocode"": ""35""}".ToStream()) 
{ 
    responseStream = stringstream; 
} 
var webresponse = new Mock<WebResponse>(); 
webresponse.Setup(c => c.GetResponseStream()).Returns(responseStream); 

authMock.Setup((x) => x.UserAuthentification(It.IsAny<string>(), It.IsAny<string>())). 
      Throws(new WebException("fu", null,WebExceptionStatus. TrustFailure, webresponse.Object)); 

sut.GetUserAuthentification(It.IsAny<string>(), It.IsAny<string>(), (s) => response = s); 

//Asserts here 

將引發WebException被拋出,但是當我試圖抓住它在我的SUT和嘗試讀取一個ArgumentException被拋出流:

ex.Response.GetResponseStream error CS0103: The name 'ex' does not exist in the current context 

回答

1

因此,顯然這個問題與異常本身或我試圖嘲笑它的方式無關,但是由於我對C#中的Streams缺乏瞭解(我仍然不確定具體問題是什麼)。 當我不使用using語句將字符串轉換爲流時,一切正常。澄清這裏是我在這個例子中使用的擴展方法:

public static Stream ToStream(this string str) 
{ 
    var expectedBytes = Encoding.UTF8.GetBytes(str); 
    var responseStream = new MemoryStream(); 
    responseStream.Write(expectedBytes, 0, expectedBytes.Length); 
    responseStream.Seek(0, SeekOrigin.Begin); 
    return responseStream; 
} 

所以我想我會刷新我關於流的知識。

1

這就是我爲同樣的問題做

private void StubCallerToThrowNotFoundException(string iprange) 
    { 
     var response = new Mock<HttpWebResponse>(); 
     response.Setup(c => c.StatusCode).Returns(HttpStatusCode.NotFound); 

     mocker.Setup<ICaller>(x => x.GetResponseAsync(It.Is<string>(p => !p.Contains(iprange)))) 
      .Throws(new WebException("Some test exception", null, WebExceptionStatus.ProtocolError, response.Object)); 
    }