为什么我要嘲笑财产必须是虚拟的? [英] Why does the property I want to mock need to be virtual?

查看:177
本文介绍了为什么我要嘲笑财产必须是虚拟的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一些单元测试和嘲弄的一些属性使用起订量

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

现在,这是一个控制器测试(ASP.NET MVC 3)。我控制器从的抽象推导的控制器,名为在AbstractController

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

该控制器对HTTP上下文的依赖(为了做这样的事情的主题化,特定领域的逻辑基于HTTP主机头,等等)。

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

这是通过一个称为属性来完成的 WebSiteSettings

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

然后,我创建了一个FakeWebSiteSettings,它嘲笑HTTP上下文,以便它读取HTTP标头。

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

问题是,当我运行测试,我得到一个 NotSupportedException异常:

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

非虚拟(VB中重写)成员无效设置为:x => x.WebSiteSettings

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

下面是有关的嘲讽code:

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

如果我让 WebsiteSettings 属性的虚拟 - 测试通过

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?

推荐答案

起订量和其他类似的嘲弄框架只能模拟接口,抽象方法/属性(抽象类)或虚拟方法/属性的具体类。

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.

这篇关于为什么我要嘲笑财产必须是虚拟的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆