Dependency injection has proven to be something a black belt unit tester must know about if you are serious about unit testing. If you have written some sort of unit tests, would you be jealous if I tell you for some of us, running all these unit tests takes sub-1 second? In C# and Java, actively practising Dependency Injection makes mocking and stubbing out dependencies much easier, and thus tests become easy to write, and run fast because they do not need to make time consuming calls. In fact, constructor injection is one of my favourite design techniques:
public class Laptop
private IBattery battery;
public Laptop(IBattery battery)
this.battery = battery;
public void PowerOn()
if (battery.Meter >= 10)
// Booting Vista...
Then to unit test Laptop, you could use NMock like such:
public void PowerOnFailsWhenBatteryIsTooLow()
mocks = new Mockery();
mockBattery = mocks.NewMock<IBattery>();
Laptop laptop = new Laptop(mockBattery);
It may not be worth it to mock out Battery, but think about a lengthy web service class.
That's all true in C# and Java. Now in Ruby, I don't even need to constructor inject my Battery instance to unit test my Laptop class. I can just as easily unit test my Laptop class without having to inject my mock Battery:
@battery = Battery.new
if @battery.meter >= 10
# Booting Max OS X
class LaptopTest < Test::Unit::TestCase
laptop = Laptop.new
assert_equal :off, laptop.power_status
Basically I am mocking using Ruby Stubba/Mocha, but I don't even need to write an extra constructor to inject the Class Under Test's dependencies! With no interface IBattery, nothing! This is some cool trickery of programming in a dynamic language like Ruby, and I am discovering these things every day with my colleagues!
I know you are going to say "well, I can use reflection to do the same thing...", and I will tell you, sure, you try to do it in a readable manner and with one line of code. I didn't say you can't do it with C# or Java, I am just saying, this is how I can do it with one line of highly readable Ruby. Happy programming.