模拟Webexception包括Webresponse

时间:2015-11-24 10:04:52

标签: c# moq xunit

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

答案 0 :(得分: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 :(得分: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));
    }