我正在尝试编写一个单元测试,其中我的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 hereWebexception正在抛出,但当我试图在sut中捕获它并试图读取流时,就会抛出一个ArgumentException:
ex.Response.GetResponseStream error CS0103: The name 'ex' does not exist in the current context 发布于 2016-07-15 06:37:30
这就是我为同一个问题所做的
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));
}发布于 2015-11-24 13:15:07
因此,这个问题显然与异常本身或我试图嘲弄它的方式无关,而是与我对C#中的流缺乏理解有关(我仍然不知道确切的问题是什么)。当我在将字符串转换为流时不使用using语句时,一切都很好。为了澄清,这里是我在示例top中使用的扩展方法:
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;
}所以我想我会更新我对溪流的知识。
https://stackoverflow.com/questions/33890651
复制相似问题