什么是单元测试范围?

发布于 2024-10-19 07:56:59 字数 559 浏览 1 评论 0原文

我相信单元测试的有用性,但我真的不明白这些规则。

如果我有一个类与另一个类链接,则

public class MyClass
{       
    private SecondClass MySecondClass;

    public MyClass()
    {
        this.MySecondClass = new SecondClass ();
    }
}

该字段是私有的,并且 Myclass 有一个这样的方法:

    public ThirdClass Get()
    {
        return this.MySecondClass.Get();
    } 

我如何测试这个?我假设我必须测试 MyClass.get() 方法是否可以很好地调用 MySecondClass.Get()!但我无法模拟 SecondClass 并将其分配给第一个,因为它是一个私有字段..所以我真的想知道如何测试它..

谢谢

I am persuaded of usefulness of unit tests but I really don't understand rules for these ones..

If I have a class linked with another

public class MyClass
{       
    private SecondClass MySecondClass;

    public MyClass()
    {
        this.MySecondClass = new SecondClass ();
    }
}

the field is private, and the Myclass have a method like this:

    public ThirdClass Get()
    {
        return this.MySecondClass.Get();
    } 

How can I test this?? I assume I have to test if the MyClass.get() method is well calling MySecondClass.Get()! But I can't make a mock of SecondClass and assign it to the first one because it is a Private field.. So I really wonder how is possible to test this..

Thanks

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

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

发布评论

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

评论(1

心房的律动 2024-10-26 07:56:59

您无法轻松对其进行单元测试,因为实例化是硬编码的。您可以在可以模拟它的地方使用构造函数注入:

public class MyClass
{       
    private SecondClass _mySecondClass;

    public MyClass(SecondClass mySecondClass)
    {
        _mySecondClass = mySecondClass;
    }

    public ThirdClass Get()
    {
        return _mySecondClass.Get();
    } 
}

现在在单元测试中您可以提供您喜欢的此类的任何实例。这就是控制反转的原理。类不再负责实例化其依赖项,而是传递依赖项的那些类的使用者。

You cannot easily unit test this because the instantiation is hardcoded. You could use constructor injection where you could mock it:

public class MyClass
{       
    private SecondClass _mySecondClass;

    public MyClass(SecondClass mySecondClass)
    {
        _mySecondClass = mySecondClass;
    }

    public ThirdClass Get()
    {
        return _mySecondClass.Get();
    } 
}

Now in your unit test you could supply any instance of this class you like. That's the principle of Inversion of Control. Classes are no longer responsible for instantiating its dependencies, its the the consumer of those classes that passes the dependencies.

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