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?

2
  • Try looking at stackoverflow.com/questions/9823039/… Commented Feb 14, 2015 at 1: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' Commented Feb 14, 2015 at 1:54

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.