Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking out a local variable in C#

I have a C# class which instantiates on its own a NetworkCommunicator class. I'd like to mock out the NetworkCommunicator class for my unit test, and replace it with a pretty simple stub.

But the NetworkCommunicator is never passed as a parameter. It's created by the class being tested.

In Ruby, this is easy to mock out. In Java, this is why you need Dependency Injection, which is too heavy for this project. Is there a simple way to mock this out in C#, perhaps using Moq or something similar?

like image 857
SRobertJames Avatar asked Jun 20 '26 02:06

SRobertJames


1 Answers

You mentioned that DI is too heavyweight for this project, why not try some Truck Driver's DI, thus:

public interface IDependency
{
    void DoSomeStuff();
}

public class ClassUnderTest
{
    private IDependency _dependency;

    public ClassUnderTest(IDependency dependency)
    {
        _dependency = dependency;
    }

    public ClassUnderTest() : this(new Dependency())
    {}

    public void ImportantStuff()
    {
        _dependency.DoSomeStuff();
    }
}

Using this constructor chaining technique, you can now mock the IDependency all you want, without worrying about hooking up DI or IoC.

like image 172
Greg Smith Avatar answered Jun 22 '26 14:06

Greg Smith



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!