Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


1 Answers

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.

like image 165
Darin Dimitrov Avatar answered Mar 07 '26 19:03

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!