模拟Webexception,包括Webresponse



我正在尝试编写一个单元测试,其中我的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   

这是我对同一个问题所做的

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

很明显,这个问题与异常本身或我试图模拟它的方式无关,而是我对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;
}

所以我想我会刷新我对流的知识。

相关内容

  • 没有找到相关文章

最新更新