I am doing some unit tests and mocking some properties using Moq .
Now this is the Test Controller (ASP.NET MVC 3). My controllers come from an abstract controller called AbstractController .
This controller is dependent on the Http Context (in order to do such things as topics, domain-specific logic, based on HTTP HOST headers, etc.).
This is done using the WebSiteSettings property:
public abstract class AbstractController : Controller { public WebSiteSettings WebSiteSettings { get; private set; }
Pay attention to a private set - ctor installs it. So, I changed it to use an interface, and what I made fun of:
public IWebSiteSettings WebSiteSettings { get; private set; }
Then I created a “FakeWebSiteSettings” that mocks the Http content to read the HTTP headers.
The problem is that when I run the test, I get a NotSupportedException:
Incorrect setting for a non-virtual (redefined in VB) member: x => x.WebSiteSettings
Here is the corresponding mocking code:
var mockWebSiteSettings = new Mock<FakeWebSiteSettings>(); var mockController = new Mock<MyController>(SomeRepository); mockController.Setup(x => x.WebSiteSettings).Returns(mockWebSiteSettings.Object); _controller = mockController.Object; var httpContextBase = MvcMockHelpers.FakeHttpContext(); httpContextBase.Setup(x => x.Request.ServerVariables).Returns(new NameValueCollection { {"HTTP_HOST","localhost.www.mydomain.com"}, }); _controller.SetFakeControllerContext(httpContextBase.Object);
If I create the WebsiteSettings virtual property, the test passes.
But I can’t understand why I need it. I do not redefine the property, I just mock how it is configured.
Am I missing something or did it wrong?
c # unit-testing asp.net-mvc moq controller
RPM1984 Apr 14 2018-11-11T00: 00Z
source share