rhughes
rhughes

Reputation: 9583

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.

Upvotes: 8

Views: 8950

Answers (2)

Scott Wegner
Scott Wegner

Reputation: 7493

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);

Upvotes: 5

rhughes
rhughes

Reputation: 9583

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);

Upvotes: 4

Related Questions