user3079474
user3079474

Reputation: 1793

Is it possible to mock newly created instances for a given class in C#?

I have a class that takes in a configuration object as a parameter of the constructor and then creates new objects in the constructor using that configuration. So generally, is it possible to mock the newly created object without explicit dependency injection?

Relevant portions of the code are:

public class Manager
{
    List<Config> _configList;
    List<StateObject> _stateObjectList;

    public Manager(List<Config> configList)
    {
        _configList = configList;

        foreach (config in _configList)
        {
           _stateObjectList.Add(new StateObject(config));
        }
    }
}

Specifically, can I somehow mock the returned new StateObject inside the foreach loop in the constructor?

I'm using .NET Framework 4.7.2 with Moq 4.10 if its relevant

Upvotes: 0

Views: 121

Answers (1)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23228

I don't think that you can mock new operator in C#, but you can slightly refactor your code and move a creation of StateObject into separate class (and create an interface for that)

public interface IStateObjectFactory
{
    StateObject Create(Config config);
}

public class StateObjectFactory : IStateObjectFactory
{
    public StateObject Create(Config config)
    {
        return new StateObject(config);
    }
}

Then you can pass it to a Manager class

public Manager(List<Config> configList, IStateObjectFactory factory)
{
    _configList = configList;

    foreach (var config in _configList)
    {
        _stateObjectList.Add(factory.Create(config));
    }
}

This approach allows you to easily mock IStateObjectFactory interface with any desired behavior. I don't think that it's possible without injecting this dependency into Manager class.

Upvotes: 2

Related Questions