It’s almost always practically impossible to test a class without instantiating other classes on which it depends or interacts. What can be done is mocking objects: creating “empty objects” that emulate the external behaviour of real objects. They must be able to “fool” the class under test and allow the creation of an exhaustive set of tests around it.

Since the class under tests “expects” the other classes to do something, here comes the term expectation: the unit test expects that the class under test uses the mock object by calling a specific method, optionally in a specific order and optionally with specific arguments and return values.

An example with PHPUnit, where the class under test Person depends on a class Company, which is mocked:

In this silly example, we are testing Person, and we want to verify that on the first day of work with a company, that person has a laptop assigned.Person is actually instantiated, but Company, possibly a bigger and more complicated class, with other dependencies, is just mocked.What we check is that inside Person::startFirstDay(), there’s at least one call to Company::giveLaptop().

As mentioned at the beginning of this article, expectations are available on Perl too, with the module Test::Expectation. The equivalent of the example before could be:

(Note that Test::Expectation uses internally Test::More with a plan, so if you’re using Test::Expectation AND Test::More you can’t set a plan with the latter, as perl will complain that there’s already a plan set by the former)

Unfortunately Test::Expectation is not available as a standard debian package, so if needed you may debianize it (just download, untar, dh-make-file and debuild. I wrote this article with some basic instructions).

Disclaimer:- The code in this article can't work as is, i.e. it needs modules to be installed and configured, and more lines to include those modules.- The code in this article has not been tested, and it doesn't come with any warranty- I'm not implying that a company should provide each employee with a laptop during their first day