本文介绍了最小起订量要求?击败目的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否不需要虚拟化您要模拟的所有属性访问器,从而破坏了模拟的目的?

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?

推荐答案

您的问题非常有效,但是如果您考虑一下,就没有其他方法可以模拟类了.如果使用接口,则仅是合同,因此模拟框架可以模拟您想要的方式,但是如果您使用类,则该接口已经为其成员提供了一个实现.

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

现在拥有

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

现在打电话给你

foo.Bar();

您不希望它调用实际的实现,但是由于它不是虚拟成员,因此它将调用FooBar()

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

打电话

foo.VirtualBar();

将调用MockFooVirtualBar(),因为它是一个虚拟成员,将具有按要求由模拟框架注入的行为.

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

这篇关于最小起订量要求?击败目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:57