Moq - setting HttpResponse

I am trying to mock an 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 tried using Setup().Returns()and SetupGet(), but I keep getting the following error:

'The property or index element' System.Web.HttpContextBase.Response 'cannot be assigned - it is read-only.

I tried Google and searched this site, but I can not find the answer.

+5
source share
2 answers

It seems that I did not pass the correct object to the method Returns(). I had to pass the mock property Object.

Here is the correct code:

var context = new Mock<HttpContextBase>();
var response = new Mock<HttpResponseBase>();

context.Setup(c => c.Response).Returns(response.Object);
+3
source

get-only SetupGet(..) .Returns(..) :

var context = new Mock<HttpContextBase>();
var response = new Mock<HttpResponseBase>();

context.SetupGet(c => c.Response)
       .Returns(response.Object);
+3

All Articles