I am trying to Mock a HttpResponse for a ConrollerContext object using MVC 4, Moq 4 and C# 4.5
My code is here:
var context = new Mock<HttpContextBase>();
var response = new Mock<HttpResponseBase>();
context.SetupProperty(c => c.Response = response);
I have tried using Setup().Returns()
and SetupGet()
but I keep getting the following error:
"Property or Indexer 'System.Web.HttpContextBase.Response' cannot be assigned to -- it is read only.
I have tried Googling this and searching on this website, but I can't seem to find the answer.
For get-only properties, use SetupGet(..)
, and specify a .Returns(..)
clause with the return value to inject:
var context = new Mock<HttpContextBase>();
var response = new Mock<HttpResponseBase>();
context.SetupGet(c => c.Response)
.Returns(response.Object);
It seems that I did not pass the correct object into the Returns()
method. I should have passed the mock's Object
property.
Here is the correct code:
var context = new Mock<HttpContextBase>();
var response = new Mock<HttpResponseBase>();
context.Setup(c => c.Response).Returns(response.Object);
If 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