起订量要求?违背了目的?

发布于 2024-11-05 08:42:47 字数 97 浏览 3 评论 0原文

是否需要虚拟化您想要模拟的所有属性访问器就违背了模拟的目的?

我的意思是,如果我必须修改我的对象并虚拟化我想要模拟的每个访问器,我难道不能继承我的类并自己模拟它吗?

Doesn't being required to virtualize all property accessors you want to mock kind of defeat the purpose of mocking?

I mean, if I have to modify my object and virtualize every single accesor I want to mock, couldn't I just as well inherit my class and mock it myself?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

执手闯天涯 2024-11-12 08:42:47

你的问题非常有效,但如果你仔细想想,没有其他方法可以模拟课程。如果你采用一个接口,它只是一个契约,所以模拟框架可以模拟你想要的方式,但如果你采用一个类,它已经有它的成员的实现。

因此,模拟框架为了能够模拟类成员,必须从类继承并根据请求覆盖成员的行为,为此只有虚拟成员才能工作。

例如。如果你有(我正在展示方法,但属性也是如此)

class Foo
{
    public void Bar()
    {

    }
    public virtual void  virtualBar()
    {

    }
}

,那么模拟框架可能会创建类似这样的东西来模拟

public class MockFoo : Foo
{
    public override void virtualBar()
    {
        // mockery action
    }

    public new void Bar()
    {
        // mockery action
    }
}

Now 当你有

Foo foo = GetMockObject(); // you get an instance of MockFoo

now 当你调用时,

foo.Bar();

你不打算让它调用实际的实现,但因为它是一个非虚拟成员,它会调用FooBar()

另一方面,调用

foo.VirtualBar();

会调用MockFooVirtualBar() 因为它是一个虚拟成员,它将具有模拟框架根据请求注入的行为。

Your question is very valid but if you think about it,there is no other way to mock a class. If you take an interface, it's just a contract so the mock framework can mock how ever you want it but if you take a class, it already has an implementation for it's members.

So the mock framework, in order to be able to mock the class members, has to inherit from the class and override the member's behavior as requested and for this purpose only virtual members will work.

For eg. if you have (I'm showing methods but the same is true for properties)

class Foo
{
    public void Bar()
    {

    }
    public virtual void  virtualBar()
    {

    }
}

then the mock framework probably creates something like this to mock

public class MockFoo : Foo
{
    public override void virtualBar()
    {
        // mockery action
    }

    public new void Bar()
    {
        // mockery action
    }
}

Now when you have

Foo foo = GetMockObject(); // you get an instance of MockFoo

now when you call

foo.Bar();

you don't intend for it to call the actual implementation but since it's a non virtual member, it will call the Foo's Bar()

on the other hand, calling

foo.VirtualBar();

would call MockFoo's VirtualBar() as it's a virtual member which would have the behavior injected by the mock framework as requested.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文