gpt4 book ai didi

c# - 模拟 Webexception,包括 Webresponse

转载 作者:行者123 更新时间:2023-11-30 23:33:34 25 4
gpt4 key购买 nike

我正在尝试编写一个单元测试,其中我的 sut (authMock) 的依赖项应该抛出一个具有特定响应的 Webexception(将在 sut 中相应地解析的 json)。但是,我无法像这样使用 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# - 模拟 Webexception,包括 Webresponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33890651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com