Therefore, all classes in moam.be are derived from an interface. When a class depends on another class, then it uses that class though the interface instead of directly. With moose, these interfaces are of course roles.
- The role
- The implementation
- The depending class
So now, CrawlerApp::CrawlerService will be set to CrawlerService in the actual application (either via dependency injection, or just manually). But when I'm testing, I can just replace that with a mock object that also implements the ICrawlerService role (I use Test::Mock::Class for this).
This is all really cool, but what if I want to mock out part of a class instead of an entire class.
Something like this:
Unit testing learns us that each unit of code must be tested separately. So if I want to test the A-method properly, I need to find a way to mock out the B-method.
As a side note: At work I program in C# and we use Rhino.Mocks as our mock library. The example above is something that cannot be done with Rhino.Mocks. This means that you need to make your own hand-crafted mock-implementation of the class under test and that you have to override the behaviour of the B-method in that derived class. This is a lot of work for a simple test and has frustrated me on numerous occasions! So you can imagine how overjoyed I was when I found out that perl does have way to do this:
This wonderfull module allows me to do this in my test code:
TADAAAAAAAAA: I can test the A-method without being annoyed by its dependency of the B-method! As a plus, I can even check to make sure that the A-method did in fact call the B-method.
I like it.