Unit Testing – How to Perform Unit Testing Without Dependency Injection

asp.net-mvccunit testing

I am starting a small ASP.NET MVC project, each task on the board must come with unit tests. The project is small, just a few pages with not that much processing, so I decided not to implement DI. My thoughts being DI is for larger projects with dependency graphs.

However, now I am writing tests it has made me realise testing is more difficult. There is no constructor injection going on, so mocking these objects being used by the controller actions is proving troublesome.

If there are objects being instantiated on the action due to lack of contructor injection how can you mock them to test?

Best Answer

Here's a question: does this look like DI?

public class MyCar
{
    private IEngine _engine;

    public MyCar(IEngine engine)
    {
        _engine = engine;
    }

    public MyCar()
        : this(new MyV8Engine())
    {

    }
}

It should, because it IS DI. Dependency Injection is about injecting a dependency into an object, instead of placing the burden of new'ing up or finding the dependency on the object that requires it. DI is not about using a framework, it is a design pattern that solves an issue.

It is very valid for small applications to use constructor-based injection and new'ing up objects in default constructors. The reason you don't see this as an example of DI is because often times your dependency graph quickly becomes very big and unwieldy and the move to a DI framework rapidly becomes advantageous as your application grows.