1

I'm stuck on how to set the contentencoding property as it is not overridable via moq.

I currently have the following:

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");

But I get the following exception:

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

Any idea how I can mock this property?

chouaib
  • 2,763
  • 5
  • 20
  • 35
Imran Azad
  • 1,008
  • 2
  • 12
  • 30
  • Try looking at http://stackoverflow.com/questions/9823039/is-it-possible-to-mock-out-a-net-httpwebresponse – Ilya Kogan Feb 14 '15 at 01:30
  • @IlyaKogan Thanks, I had a look at that before however even with that example code the ContentEncoding prperty throws `'response.ContentEncoding' threw an exception of type 'System.NullReferenceException'` – Imran Azad Feb 14 '15 at 01:54

1 Answers1

2

This is what i would do:

      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);

Add that instead of your last line.

zaitsman
  • 8,984
  • 6
  • 47
  • 79
  • Wow! I went to bed disheartened but woke up to find your answer works like a charm! One thing I don't get though is, how is the webresponse class picking the content-encoding, because your code doesn't appear to be passed anywhere, is it something to do with the Set and SetValue methods? – Imran Azad Feb 14 '15 at 08:44
  • @ImranAzad This code uses reflection. if you use at `HttpWebResponse.ContentEncoding` property you will see that it just returns a header out of private field collection, so that is what we got to set to get the outcome that you want. – zaitsman Feb 14 '15 at 23:48