Possible duplicate:
Using IoC for Unit Testing
I think I have a problem understanding how Unit tests and / or Dependency Injection tests work. I use NUnit and Rhino Mocks for unit testing and Ninject as an Injection Dependency platform. In general, I, although these two will come to perfection, but for some reason it seems that it is becoming more complex and difficult to understand.
(I will try to make a good example so that it is clean and easy. It's about me, cycling).
1.) Without DI / Unit tests:
Unaware of the DI and Unit Tests, my code would look like this - and I would be happy:
public class Person { public void Travel() { Bike bike = new Bike(); bike.Ride(); } } public class Bike { public void Ride() { Console.WriteLine("Riding a Bike"); } }
To ride my bike, I just need: new Person().Travel();
2.) With DI:
I don't want this hard link, so I need an interface and a NinjectModule! I would have a bit of Overhead, but it would be nice if the code is easy to read and understand. I just pass the code for the modified Person class, the Bike class will not change:
public class Person { IKernel kernel = new StandardKernel(new TransportationModule()); public void Travel() { ITransportation transportation = kernel.Get<ITransportation>(); transportation.Ride(); } }
I could still ride my bike with: new Person().Travel();
3.) Consideration of Unit-Testing (without DI):
To check if the Ride-Method is called correctly, I will need a Mock. As far as I know, there are two ways to introduce an interface: constructor injection and setter injector. I choose Constructor Injection for my example:
public class Person { ITransportation transportation; public person(ITransportation transportation) { this.transportation = transportation; } public void Travel() { transportation.Ride(); } }
This time I would ask to go through the bike: new Person(new Bike()).Travel();
4.) With DI and Unit-Tests preparation
A class in 3. Considering Unit-Testing (without DI) would do the job unchanged, but I would need to call new Person(kernel.Get<ITransportation>()); . Thanks to this, I feel that I am losing the benefit of DI - the Person class could call Travel without any connection and any need to know which class the transport is. In addition, I think that this form lacks the readability of Example 2.
Is this how it is done? Or are there other - more elegant ways to achieve Injection Dependency and the ability to unit test (and mock)?
(Looking back, it seems that the example is really bad - everyone should know which transport device he is traveling at the moment ...)