Reputation: 307
We have a controller,which has a contructor accepting another class object. For example,
ABCController(IXyz obj){this.xyz = obj;}
Now,in the unit test,while instantiating the conroller,we do something like this:
ABCController controller = new ABCController (new Xyz());
We are injecting the dependency from the unit test project and after this we are able to test all the methods of the Controller.
Now the big question is,what is the standard way of instantiating the controller rather than supplying/injecting the dependency?
I agree that this is the reason there are plenty of mocking/testing frameworks exists.But do we need to adopt to a new framework altogther just to avoid injecting the dependency? or injecting is the best trade off rather than adopting a new framework altogether?
Please advise/clarify.
Upvotes: 0
Views: 94
Reputation: 67316
There are two contexts in which to answer this question. First, how to decide what objects (mocks or stubs) when testing. Second, how to configure what dependencies to inject in the application.
1. When Testing
When testing (and I mean unit testing mostly), you often want to isolate the code that is under test from the dependencies. Here a mocking framework (Moq, NSubstitute, Rhino Mocks etc) comes in handy. These mock a dependency and allow you to further separate the code under test from changing dependencies.
Note, you could create stub class implementations for every interface that needs to be injected. But, this might be tedious to maintain on a large project. However, some projects prefer to do something like this. Mocking frameworks often provide functionality above just stubbing, however. They provide interaction-based assertions that can record and playback actions that occur on the dependencies. Once recorded, these actions can then be the basis for test assertions. For example, how many times a particular dependency was called, etc.
2. For The Application
At runtime, an application that uses dependency injection, needs a way to configure and resolve dependencies. The application configuration of dependencies defines the "Inversion of Control" for the application process. In this context, an inversion of control container (Ninject, Castle Windsor, StructureMap etc) is often brought in to help manage the configuration and resolution of dependencies.
Hope this helps.
Upvotes: 1
Reputation:
The point of dependency injection is that you want to inject the dependency. All the mocking frameworks do is help you create a mock object to inject to test against, rather than needing to create new test objects yourself with lots of boilerplate code.
It's not really a good idea to use a container or DI framework to create your controllers in your tests IMO, because you should know the mock objects and what you are creating.
So you're doing it right, but use Moq or Autofixture to create a mock IXyz to test against rather than creating one longhand each time.
Upvotes: 1