首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模拟Webexception,包括Webresponse

模拟Webexception,包括Webresponse
EN

Stack Overflow用户
提问于 2015-11-24 10:04:51
回答 2查看 2.6K关注 0票数 4

我正在尝试编写一个单元测试,其中我的sut (authMock)的依赖项应该抛出一个带有特定响应的Webexception (json,将相应地在sut中进行解析)。但是,我在使用Moq抛出Webexception时遇到了困难,比如:

代码语言:javascript
复制
 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:

代码语言:javascript
复制
    ex.Response.GetResponseStream   error CS0103: The name 'ex' does not exist in the current context   
EN

回答 2

Stack Overflow用户

发布于 2016-07-15 06:37:30

这就是我为同一个问题所做的

代码语言:javascript
复制
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));
    }
票数 3
EN

Stack Overflow用户

发布于 2015-11-24 13:15:07

因此,这个问题显然与异常本身或我试图嘲弄它的方式无关,而是与我对C#中的流缺乏理解有关(我仍然不知道确切的问题是什么)。当我在将字符串转换为流时不使用using语句时,一切都很好。为了澄清,这里是我在示例top中使用的扩展方法:

代码语言:javascript
复制
 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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33890651

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档