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)
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,
HttpWebRequest
(e.g. IHttpClient
) and use that in your unit testsIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With