Mocking HttpWebRequest Accept with Moq
本文关键字:Moq with Accept HttpWebRequest Mocking | 更新日期: 2023-09-27 18:24:02
我正在使用Moq模拟HttpWebRequest。我能够模拟Header&方法,但当我试图嘲笑Accept时,它就爆炸了。
代码为:
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");
例外情况是:
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)
使用Moq无法实现您想要做的事情。Moq不能模拟具体实现的非虚拟方法(使用IInterface
也可以)。
,你有几个选择
- 创建一个使用
HttpWebRequest
(例如IHttpClient
)实现的简单接口,并在单元测试中使用它 - 使用不同的嘲讽框架(看看这篇文章的想法)