模拟WebException包括WebResponse

4

我试图编写一个单元测试,其中我sut的依赖项(authMock)应该抛出一个特定响应的Webexception(JSON将在sut中解析)。然而,我在使用Moq时遇到了抛出Webexception的问题:

 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   
2个回答

3

这是我为同样的问题所做的工作

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

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

所以我想我会重新学习关于流的知识。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接