Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq - Setting HttpResponse

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.

like image 812
rhughes Avatar asked Sep 01 '12 06:09

rhughes


2 Answers

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);
like image 60
Scott Wegner Avatar answered Oct 06 '22 20:10

Scott Wegner


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);
like image 36
rhughes Avatar answered Oct 06 '22 21:10

rhughes