DenaliHardtail
DenaliHardtail

Reputation: 28326

How do I correctly instantiate a new controller when using Ninject?

I created a demo Web API application that utilizes Ninject. The application works fine as I can run it, navigate to the defined route, and get the data I'm expecting. Now I want to begin adding unit tests to test the ApiController.

How do I instantiate a new ApiController? I'm using var sut = new DogsController(); but that results in an error, "... does not contain a constructor that take 0 arguments". It's correct I don't have a constructor that takes 0 arguments but Ninject should be taking care of that for me, correct? How do I resolve this?

Upvotes: 0

Views: 104

Answers (2)

Steven
Steven

Reputation: 172716

A DI container is not some piece of magic that transforms your code every time you write "new Something()". In your unit test you are newing up the controller by hand (which is good practice btw), but this means you will have to supply the constructor with the proper fake versions of the abstractions the constructor expects.

Upvotes: 0

adrianbanks
adrianbanks

Reputation: 82974

You will have wired Ninject into the Web API application, not your unit test project. As a result, Ninject will not be creating the dependencies for your controller, or even your controller as you are explicitly creating it (in the Web API application, the framework creates your controller).

You could wire Ninject into your unit test project, but that would not be the correct thing to do. You should be creating your controller in your tests with a known state, so you should either be passing in known dependencies, or passing in some form of mock dependencies.

Upvotes: 1

Related Questions