Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

c# - Why does the property I want to mock need to be virtual?

I'm doing some unit testing, and mocking some properties using Moq.

Now, this is a Controller test (ASP.NET MVC 3). My Controllers derive from an abstract controller, called AbstractController.

This controller has a dependency on the Http Context (in order to do things like theming, domain-specific logic based on HTTP HOST headers, etc).

This is done via a property called WebSiteSettings:

public abstract class AbstractController : Controller
{
   public WebSiteSettings WebSiteSettings { get; private set; }

   // other code
}

Notice the private set - the ctor sets it up. So, i changed it to used an interface, and that's what i've mocked:

public IWebSiteSettings WebSiteSettings { get; private set; }

I then created a "FakeWebSiteSettings", which mocks the Http Context in order for it to read the HTTP headers.

The problem is, when i run the test, i get a NotSupportedException:

Invalid setup on a non-virtual (overridable in VB) member: x => x.WebSiteSettings

Here's the relevant 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 make the WebsiteSettings property virtual - the test passes.

But i can't understand why i need to do this. I'm not actually overriding the property, i'm simply mocking how it is setup.

Am i missing something, or doing this wrong?

question from:https://stackoverflow.com/questions/5670902/why-does-the-property-i-want-to-mock-need-to-be-virtual

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Moq and other similar mocking frameworks can only mock interfaces, abstract methods/properties (on abstract classes) or virtual methods/properties on concrete classes.

This is because it generates a proxy that will implement the interface or create a derived class that overrides those overrideable methods in order to intercept calls.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...