5

I'm using Moq to mock a HttpWebRequest. I'm able to mock Headers & Method but it blows up when I try to mock Accept.

Code is:

 Mock<HttpWebResponse> response = new Mock<HttpWebResponse>(MockBehavior.Loose); Mock<HttpWebRequest> request = new Mock<HttpWebRequest>(); request.Setup(s => s.GetResponse()).Returns(response.Object); request.Setup(m => m.Method).Returns("GET"); request.Setup(h => h.Accept).Returns("application/x-protobuf"); 

Exception is:

 System.NotSupportedException was unhandled by user code HResult=-2146233067 Message=Invalid setup on a non-virtual (overridable in VB) member: h => h.Accept Source=Moq StackTrace: at Moq.Mock.ThrowIfCantOverride(Expression setup, MethodInfo method) at Moq.Mock.<>c__DisplayClass1f`2.<SetupGet>b__1e() at Moq.PexProtector.Invoke[T](Func`1 function) at Moq.Mock.SetupGet[T,TProperty](Mock mock, Expression`1 expression, Func`1 condition) at Moq.Mock.<>c__DisplayClass1c`2.<Setup>b__1b() at Moq.PexProtector.Invoke[T](Func`1 function) at Moq.Mock.Setup[T,TResult](Mock mock, Expression`1 expression, Func`1 condition) at Moq.Mock`1.Setup[TResult](Expression`1 expression) at HarmonyTests.MockWebRequestCreate.CreateTestRequest(Stream protobuf) 
1
  • Related question Commented Sep 23, 2014 at 19:12

1 Answer 1

3

What you are trying to do is not possible using Moq. Moq cannot mock a non-virtual method of a concrete implementation (using an IInterface would be fine).

You have a couple of options,

  1. Create a simple interface that is implemented using HttpWebRequest (e.g. IHttpClient) and use that in your unit tests
  2. Use a different mocking framework (take a look at this post for ideas).
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.