NAME
Test::MockClass - A module to provide mock classes and mock objects for testing
SYNOPSIS
# Pass in the class name and version that you want to mock
use Test::MockClass qw{ClassToMock 1.1};
# create a MockClass object to handle a specific class
my $mockClass = Test::MockClass->new('ClassToMock');
# specify to inherit from a real class, or a mocked class:
$mockClass->inheritFrom('IO::Socket');
# make a constructor for the class, can also use 'addMethod' for more control
$mockClass->defaultConstructor(%classWideDefaults);
# add a method:
$mockClass->addMethod('methodname', $coderef);
# add a simpler method, and specify return values that it will return automatically
$mockClass->setReturnValues('methodname2', 'always', 3);
# create an instance of the mocked class:
my $mockObject = $mockClass->create(%instanceData);
# set the desired call order for the methods:
$mockClass->setCallOrder('methodname2', 'methodname', 'methodname');
# run tests using the mock Class elsewhere:
#:in the class to test:
sub objectFactory {
return ClassToMock->new;
}
#:in your test code:
assert($testObj->objectFactory->isa("ClassToMock"));
# get the object Id for the rest of the methods:
my $objectId = "$mockObject";
#or
$objectId = $mockClass->getNextObjectId();
# verify that the methods were called in the correct order:
if($mockClass->verifyCallOrder($objectId)) {
# do something
}
# get the order that the methods were called:
my @calls = $mockClass->getCallOrder($objectId);
# get the list of arguments passed per call:
my @argList = $mockClass->getArgumentList($objectId, 'methodname', $callPosition);
# get the list of accesses made to a particular attribute (hashkey in $mockObject)
my @accesses = $mockClass->getAttributeAccess($objectId, 'attribute');
EXPORTS
Nothing by default.
REQUIRES
The Hook::WrapSub manpage, the Tie::Watch manpage, the Scalar::Util manpage.
DESCRIPTION
This module provides a simple interface for creating mock classes and mock objects with mock methods for mock purposes, I mean testing purposes. It also provides a simple mechanism for tracking the interactions to the mocked objects. I originally wrote this class to help me test object factory methods, since then, I've added some more features. This module is hopefully going to be the Date::Manip of mock class/object creation, so email me with lots of ideas, everything but the kitchen sink will go in!
METHODS
import
This method is called when you use the class. It optionally takes a list of classes to mock:
use Test::MockClass qw{IO::Socket File::Finder DBI};
You can also specify the version numbers for the classes:
use Test::MockClass qw{DBD::mysql 1.1 Apache::Cookie 1.2.1}
This use fools perl into thinking that the class/module is already loaded, so it will override any use statement within the code that you're trying to test.
new
The Test::MockClass constructor. It has one required argument which is the name of the class to mock. It also optionally takes a version number as a second argument (this version will override any passed to the use statement). It returns a Test::MockClass object, which is the interface for all of the method making and tracking for mock objects created later.
my $mockClass = Test::MockClass->new('ClassToMock', '1.1');
If no version is specified in either the use statement or the call to new, it defaults to -1.
addMethod
A mocked class needs methods, and this is the most flexible way to create them. It has two required arguments, the first one is the name of the method to mock. The second argument is a coderef to use as the contents of the mocked method. It returns nothing of value. What it does that is valuable is install the method into the symbol table of the mocked class.
$mockClass->addMethod('new', sub { my $proto = shift; my $class = ref($proto) || $proto; my $self = {}; bless($self, $class); });
$mockClass->addMethod('foo', sub {return 'foo';});
defaultConstructor
I'm often too lazy, or, er, busy to write my own mocked constructor, especially when the constructor is a simple standard one. For those times I use the defaultConstructor method. This method takes a hashy list as the optional arguments, which it passes to the constructor as class-wide default attributes/values. It installs the constructor in the mocked class as 'new' or whatever was set with $mockClass->constructor() (see that method description later in this document).
$mockClass->defaultConstructor('cat' => 'hat', 'grinch' => 'x-mas');
Of course, this assumes that your objects are based on hashes.
setReturnValues
My laziness often extends beyond the simple constructor to the methods of the mocked class themselves. Often I don't feel like writing a whole method when all I need for testing is to have the mocked method return a specific value. For times like this I'm glad I wrote the setReturnValues method. This method takes a variable number of arguments, but the first two are required. The first argument is the name of the method to mock. The second argument specifies what the mocked method will return. Any additional arguments may be used as return values depending on the type of the second argument. The possible values for the second argument are as follows:
- true
-
This specifies that the method should always return true (1).
$mockClass->setReturnValues('trueMethod', 'true'); if($mockObject->trueMethod) {}
- false
-
This specifies that the method should always return false (0).
$mockClass->setReturnValues('falseMethod', 'false'); unless($mockObject->falseMethod) {}
- undef
-
This specifies that the method should always return undef.
$mockClass->setReturnValues('undefMethod', 'undef'); if(defined $mockObject->undefMethod) {}
- always
-
This specifies that the method should always return all of the rest of the arguments to setReturnValues.
$mockClass->setReturnValues('alwaysFoo', 'always', 'foo'); $mockClass->setReturnValues('alwaysFooNBar', 'always', 'foo', 'bar');
- series
-
This specifies that the method should return 1 each of the rest of the arguments per method invocation until the arguments have all been used, then it returns undef.
$mockClass->setReturnValues('aFewGoodMen', 'series', 'Abraham', 'Martin', 'John');
- cycle
-
This specifies that the method should return 1 each of the rest of the arguments per method invocation, once all have been used it starts over at the beginning.
$mockClass->setReturnValues('boybands', 'cycle', 'BackAlley-Bros', 'OutOfSync', 'OldKidsOverThere');
- random
-
This specifies that the method should return a random value from the list. Well, as random as perl's srand/rand can get it anyway.
$mockClass->setReturnValues('userInput', 'random', (0..9));
setCallOrder
Sometimes it's important to impose some guidelines for behavior on your mocked objects. This method allows you to set the desired call order for your mocked methods, the order that you want them to be called. It takes a variable length list which is the names of the methods in the proper order. This list is then used in comparison with the actual call order made on individual mocked objects.
$mockClass->setCallOrder('new', 'foo', 'bas', 'bar', 'foo');
getCallOrder
Objects often do bizzare and unnatural things when you aren't looking, so I wrote this method to track what they did behind the scenes. This method returns the actual method call order for a given object. It takes one required argument which is the object Id for the object you want the call order of. One way to get an object's Id is to simply pass it in stringified:
my @callOrder = $mockClass->getCallOrder("$mockObject");
This method returns an array in list context and an arrayref under scalar context. It returns nothing under void context.
verifyCallOrder
Now we could compare, by hand, the differences between the call order we wanted and the call order we got, but that would be all boring and we've got better things to do. I say we just use the verifyCallOrder method and be done with it. This method takes one required argument which is the object Id of the object we want to verify. It returns true or false depending on whether the methods were called in the correct order or not, respectively.
if($mockClass->verifyCallOrder("$mockObject")) {
# do something
}
create
Sometimes you might want to use the Test::MockClass object to actually return mocked objects itself, I'm not sure why, but maybe someone would want it, so for them there is the create method. This method takes a variable sized hashy list which will be used as instance attributes/values. These attributes will ovverride any class-wide defaults set by the defaultConstructor method. The method returns a mock object of the appropriate mocked class. The only caveat with this method is that in order for the attribute/values defaulting-ovveride stuff to work you have to use the defaultConstructor to set up your constructor.
$mockClass->defaultConstructor('spider-man' => 'ben reilly');
my $mockObject = $mockClass->create('batman' => 'bruce wayne', 'spider-man' => 'peter parker');
getArgumentList
I've found that I often want to know exactly how a method was called on a mock object, when I do I use getArgumentList. This method takes three arguments, two are required and the third is often needed. The first argument is the object Id for the object you want the tracking for, the second argument is the name of the method that you want the arguments from, and the third argument corresponds to the order of call for this method (not to be confused with the call order for all the methods). The method returns an array which is a list of the arguments that were passed into the method. In scalar context it returns a reference to an array. The following example gets the arguments from the second time 'fooMethod' was called.
my @arguments = $mockClass->getArgumentList("$mockObject", 'fooMethod', 1);
If the third argument is not supplied, it returns an array of all of the argument lists.
getNextObjectId
Sometimes your mock objects are destroyed before you can get their object id. Well in those cases you can get the cached object Id from the Test::MockClass object. This method requires no arguments and returns object Ids suitable for use in any of the other Test::MockClass methods. The method begins with the object id for the first object created, and returns subsequent ones until it runs out, in which case it returns undef, and then starts over.
my $firstObjectId = $mockClass->getNextObjectId();
getAttributeAccess
Sometimes you need to track how the object's attributes are accessed. Maybe someone's breaking your encapsulation, shame on them, or maybe the access is okay. For whatever reason if you want a list of accesses for an object's underlying data structure just use getAttributeAccess method. This method takes a single required argument which is the object id of the object you want the tracking for. It returns a multi dimensional array, the first dimension corresponds to the order of accesses. The second dimension contains the actual tracking information. The first position [0] in this array describes the type of access, either 'store' or 'fetch'. The second position [1] in this array corresponds to the attribute that was accessed, the key of the hash, the index of the array, or nothing for a scalar. The third position in this array is only used when the access was of type 'store', and it contains the new value. In scalar context it returns an array ref.
my @accesses = $mockClass->getAttributeAccess("$mockObject");
print "breaky\n" if(grep {$_[0] eq 'store'} @accesses);
A second argument can be supplied which corresponds to the order that the access took place.
noTracking
Maybe my mock objects are too slow for you, what with all the tracking of interactions and such. Maybe all you need is a mock object and you don't care how it was interated with. Maybe you have to make millions of mock objects and you just don't have the memory to support tracking. Well fret not my friend, for the noTracking method is here to help you. Just call this method (no arguments required) and all the tracking will be disabled for any subsequent mock objects created. I personally like tracking, so I switch it on by default.
$mockClass->noTracking(); # no more tracking of methodcalls, constructor-calls, attribute-accesses
tracking
So you want to track some calls but not others? Fine, use the tracking method to turn tracking back on for any subsequently created mock objects.
$mockClass->tracking(); # now tracking is back on.
constructor
You want to use defaultConstructor or create, but you don't want to use 'new' as the name of your constructor? That's fine, just pass in the name of the constructor you want to use/create to the constructor method. Ugh, that's kinda confusing, an example will be simpler.
$mockClass->constructor('create'); # change from 'new'.
$mockClass->defaultConstructor(); # installs 'create'.
my $mockObject = MockClass->create(); # calls 'create' on mocked class.
inheritFrom
This method allows your mock class to inherit from other mock classes or real classes. Since it basically just uses perl's inheritence, it's pretty transparent. And yes, it does support multiple inheritence, though you don't have to use it if you don't wanna.
TODO
Figure out how to add simple export/import mechanisms for mocked classes. Make Test::MockClass less hash-centric. Stop breaking Tie::Watch's encapsulation. Provide mock objects with an interface to their own tracking. Make tracking and noTracking more fine-grained. Maybe find a safe way to clean up namespaces after the maker object goes out of scope. Write tests for arrayref and scalarref based objects. Write tests for unusual objects (regular expression, typeglob, filehandle, etc.)
SEE ALSO
- Alternatives: Test::MockObject, Test::MockMethod
- Testing systems: Test::Simple, Test::More, Test::Builder, Test::Harness
- xUnit testing: Test::SimpleUnit, Test::Unit, Test::Class
AUTHOR
Jeremiah Jordan <jjordan@perlreason.com>
Inspired by Test::MockObject by chromatic, and by Test::Unit::Mockup (ruby) by Michael Granger. Both of whom were probably inspired by other people (J-unit, Xunit types maybe?) which all goes back to that sUnit guy. Thanks to Stevan Little for the constructive criticism.
Copyright (c) 2002, 2003, 2004, 2005 perl Reason, LLC. All Rights Reserved.
This module is free software. It may be used, redistributed and/or modified under the terms of the Perl Artistic License (see http://www.perl.com/perl/misc/Artistic.html) or under the GPL.
2 POD Errors
The following errors were encountered while parsing the POD:
- Around line 247:
'=item' outside of any '=over'
- Around line 253:
You forgot a '=back' before '=head1'