简体   繁体   中英

What is unit tests scope?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM