什么是程序员的意思时,他们说,"反对的接口,而不是对象code"?。程序员、而不是、接口、对象

2023-09-02 01:27:04 作者:恰好喜欢

我已经开始了非常漫长而艰巨的任务,以学习和适用 TDD我的工作流程。我下了TDD适合在很好地与国际奥委会的原则IM pression。

I've started the very long and arduous quest to learn and apply TDD to my workflow. I'm under the impression that TDD fits in very well with IoC principles.

浏览一些TDD之后在这里SO标签的问题,我看这是一个好主意,对接口,而不是对象编程。

After browsing some of TDD tagged questions here in SO, I read it's a good idea to program against interfaces, not objects.

你能提供简单的code的这是什么的例子,以及如何将其应用在实际使用案例?简单的例子是关键,我(和其他人想学习)掌握的概念。

Can you provide simple code examples of what this is, and how to apply it in real use cases? Simple examples is key for me (and other people wanting to learn) to grasp the concepts.

太感谢了。

推荐答案

考虑:

class MyClass
{
    //Implementation
    public void Foo() {}
}

class SomethingYouWantToTest
{
    public bool MyMethod(MyClass c)
    {
        //Code you want to test
        c.Foo();
    }
}

由于的MyMethod 只接受 MyClass的,如果你要替换 MyClass的与以单元测试模拟对象,你不能。更好是使用一个接口

Because MyMethod accepts only a MyClass, if you want to replace MyClass with a mock object in order to unit test, you can't. Better is to use an interface:

interface IMyClass
{
    void Foo();
}

class MyClass : IMyClass
{
    //Implementation
    public void Foo() {}
}

class SomethingYouWantToTest
{
    public bool MyMethod(IMyClass c)
    {
        //Code you want to test
        c.Foo();
    }
}

现在,您可以测试的MyMethod ,因为它仅使用一个接口,而不是一个特定的具体实现。你可以把该接口,并从它继承您想要创建任何类型的模拟或假的,或者你可以使用任何prefab嘲讽的库,例如 Rhino.Mocks.MockRepository.StrictMock< T>(),它可以把界面和建立你的飞行模拟对象

Now you can test MyMethod, because it uses only an interface, not a particular concrete implementation. You can take that interface and inherit from it to create any kind of mock or fake that you want, or you can use any of the prefab mocking libraries, like Rhino.Mocks.MockRepository.StrictMock<T>(), which can take the interface and build you a mock object on the fly.