【问题标题】:Set ContentEncoding when mocking WebResponse模拟 WebResponse 时设置 ContentEncoding
【发布时间】:2015-04-15 04:38:11
【问题描述】:

我不知道如何设置 contentencoding 属性,因为它不能通过 moq 覆盖。

我目前有以下:

var expected = "dfgdfgdfgdfg";
var expectedBytes = Encoding.UTF8.GetBytes(expected);
var responseStream = new MemoryStream();
responseStream.Write(expectedBytes, 0, expectedBytes.Length);
responseStream.Seek(0, SeekOrigin.Begin);

var response = new Mock<HttpWebResponse>();
response.Setup(c => c.GetResponseStream()).Returns(responseStream);
response.Setup(c => c.ContentEncoding).Returns("UTF8");

但我得到以下异常:

 Result Message:    Invalid setup on a non-virtual (overridable in VB) member: c => c.ContentEncoding

知道如何模拟这个属性吗?

【问题讨论】:

  • @IlyaKogan 谢谢,我之前看过,但是即使使用该示例代码,ContentEncoding prperty 也会抛出 'response.ContentEncoding' threw an exception of type 'System.NullReferenceException'

标签: c# moq


【解决方案1】:

这就是我会做的:

      var webHeaderCollectionFieldInfo = typeof (HttpWebResponse).GetField("m_HttpResponseHeaders",
        BindingFlags.Instance | BindingFlags.NonPublic);

      var webHeaderCollection = new WebHeaderCollection();
      webHeaderCollection.Set("Content-Encoding", "cheese");
      webHeaderCollectionFieldInfo.SetValue(response.Object, webHeaderCollection);

添加它而不是最后一行。

【讨论】:

  • 哇!我沮丧地上床睡觉,但醒来发现你的答案就像一个魅力!我不明白的一件事是,webresponse 类如何选择内容编码,因为您的代码似乎没有在任何地方传递,这与 Set 和 SetValue 方法有关吗?
  • @ImranAzad 此代码使用反射。如果您使用HttpWebResponse.ContentEncoding 属性,您会看到它只是从私有字段集合中返回一个标头,因此我们必须设置它以获得您想要的结果。
猜你喜欢
  • 2010-09-10
  • 1970-01-01
  • 2010-12-26
  • 1970-01-01
  • 2014-07-26
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多