Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking HttpWebRequest Accept with Moq

Tags:

c#

moq

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)
like image 733
l15a Avatar asked Oct 20 '22 01:10

l15a


1 Answers

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).
like image 122
rae1 Avatar answered Oct 27 '22 19:10

rae1