.\" Automatically generated by Pod::Man 2.22 (Pod::Simple 3.10) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .ie \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .el \{\ . de IX .. .\} .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "Test::MockClass 3pm" .TH Test::MockClass 3pm "2009-12-09" "perl v5.10.1" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Test::MockClass \- A module to provide mock classes and mock objects for testing .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 2 \& # 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(\*(AqClassToMock\*(Aq); \& \& # specify to inherit from a real class, or a mocked class: \& $mockClass\->inheritFrom(\*(AqIO::Socket\*(Aq); \& \& # make a constructor for the class, can also use \*(AqaddMethod\*(Aq for more control \& $mockClass\->defaultConstructor(%classWideDefaults); \& \& # add a method: \& $mockClass\->addMethod(\*(Aqmethodname\*(Aq, $coderef); \& \& # add a simpler method, and specify return values that it will return automatically \& $mockClass\->setReturnValues(\*(Aqmethodname2\*(Aq, \*(Aqalways\*(Aq, 3); \& \& # create an instance of the mocked class: \& my $mockObject = $mockClass\->create(%instanceData); \& \& # set the desired call order for the methods: \& $mockClass\->setCallOrder(\*(Aqmethodname2\*(Aq, \*(Aqmethodname\*(Aq, \*(Aqmethodname\*(Aq); \& \& # 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, \*(Aqmethodname\*(Aq, $callPosition); \& \& # get the list of accesses made to a particular attribute (hashkey in $mockObject) \& my @accesses = $mockClass\->getAttributeAccess($objectId, \*(Aqattribute\*(Aq); .Ve .SH "EXPORTS" .IX Header "EXPORTS" Nothing by default. .SH "REQUIRES" .IX Header "REQUIRES" The Hook::WrapSub manpage, the Tie::Watch manpage, the Scalar::Util manpage. .SH "DESCRIPTION" .IX Header "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! .SH "METHODS" .IX Header "METHODS" .SS "import" .IX Subsection "import" This method is called when you use the class. It optionally takes a list of classes to mock: .PP .Vb 1 \& use Test::MockClass qw{IO::Socket File::Finder DBI}; .Ve .PP You can also specify the version numbers for the classes: .PP .Vb 1 \& use Test::MockClass qw{DBD::mysql 1.1 Apache::Cookie 1.2.1} .Ve .PP 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. .SS "new" .IX Subsection "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. .PP .Vb 1 \& my $mockClass = Test::MockClass\->new(\*(AqClassToMock\*(Aq, \*(Aq1.1\*(Aq); .Ve .PP If no version is specified in either the use statement or the call to new, it defaults to \-1. .SS "addMethod" .IX Subsection "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. .PP .Vb 1 \& $mockClass\->addMethod(\*(Aqnew\*(Aq, sub { my $proto = shift; my $class = ref($proto) || $proto; my $self = {}; bless($self, $class); }); \& \& $mockClass\->addMethod(\*(Aqfoo\*(Aq, sub {return \*(Aqfoo\*(Aq;}); .Ve .SS "defaultConstructor" .IX Subsection "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 \f(CW$mockClass\fR\->\fIconstructor()\fR (see that method description later in this document). .PP .Vb 1 \& $mockClass\->defaultConstructor(\*(Aqcat\*(Aq => \*(Aqhat\*(Aq, \*(Aqgrinch\*(Aq => \*(Aqx\-mas\*(Aq); .Ve .PP Of course, this assumes that your objects are based on hashes. .SS "setReturnValues" .IX Subsection "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: .IP "true" 4 .IX Item "true" This specifies that the method should always return true (1). .Sp .Vb 2 \& $mockClass\->setReturnValues(\*(AqtrueMethod\*(Aq, \*(Aqtrue\*(Aq); \& if($mockObject\->trueMethod) {} .Ve .IP "false" 4 .IX Item "false" This specifies that the method should always return false (0). .Sp .Vb 2 \& $mockClass\->setReturnValues(\*(AqfalseMethod\*(Aq, \*(Aqfalse\*(Aq); \& unless($mockObject\->falseMethod) {} .Ve .IP "undef" 4 .IX Item "undef" This specifies that the method should always return undef. .Sp .Vb 2 \& $mockClass\->setReturnValues(\*(AqundefMethod\*(Aq, \*(Aqundef\*(Aq); \& if(defined $mockObject\->undefMethod) {} .Ve .IP "always" 4 .IX Item "always" This specifies that the method should always return all of the rest of the arguments to setReturnValues. .Sp .Vb 2 \& $mockClass\->setReturnValues(\*(AqalwaysFoo\*(Aq, \*(Aqalways\*(Aq, \*(Aqfoo\*(Aq); \& $mockClass\->setReturnValues(\*(AqalwaysFooNBar\*(Aq, \*(Aqalways\*(Aq, \*(Aqfoo\*(Aq, \*(Aqbar\*(Aq); .Ve .IP "series" 4 .IX Item "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. .Sp .Vb 1 \& $mockClass\->setReturnValues(\*(AqaFewGoodMen\*(Aq, \*(Aqseries\*(Aq, \*(AqAbraham\*(Aq, \*(AqMartin\*(Aq, \*(AqJohn\*(Aq); .Ve .IP "cycle" 4 .IX Item "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. .Sp .Vb 1 \& $mockClass\->setReturnValues(\*(Aqboybands\*(Aq, \*(Aqcycle\*(Aq, \*(AqBackAlley\-Bros\*(Aq, \*(AqOutOfSync\*(Aq, \*(AqOldKidsOverThere\*(Aq); .Ve .IP "random" 4 .IX Item "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. .Sp .Vb 1 \& $mockClass\->setReturnValues(\*(AquserInput\*(Aq, \*(Aqrandom\*(Aq, (0..9)); .Ve .SS "setCallOrder" .IX Subsection "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. .PP .Vb 1 \& $mockClass\->setCallOrder(\*(Aqnew\*(Aq, \*(Aqfoo\*(Aq, \*(Aqbas\*(Aq, \*(Aqbar\*(Aq, \*(Aqfoo\*(Aq); .Ve .SS "getCallOrder" .IX Subsection "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: .PP .Vb 1 \& my @callOrder = $mockClass\->getCallOrder("$mockObject"); .Ve .PP This method returns an array in list context and an arrayref under scalar context. It returns nothing under void context. .SS "verifyCallOrder" .IX Subsection "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. .PP .Vb 3 \& if($mockClass\->verifyCallOrder("$mockObject")) { \& # do something \& } .Ve .SS "create" .IX Subsection "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. .PP .Vb 2 \& $mockClass\->defaultConstructor(\*(Aqspider\-man\*(Aq => \*(Aqben reilly\*(Aq); \& my $mockObject = $mockClass\->create(\*(Aqbatman\*(Aq => \*(Aqbruce wayne\*(Aq, \*(Aqspider\-man\*(Aq => \*(Aqpeter parker\*(Aq); .Ve .SS "getArgumentList" .IX Subsection "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. .PP .Vb 1 \& my @arguments = $mockClass\->getArgumentList("$mockObject", \*(AqfooMethod\*(Aq, 1); .Ve .PP If the third argument is not supplied, it returns an array of all of the argument lists. .SS "getNextObjectId" .IX Subsection "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. .PP .Vb 1 \& my $firstObjectId = $mockClass\->getNextObjectId(); .Ve .SS "getAttributeAccess" .IX Subsection "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. .PP .Vb 2 \& my @accesses = $mockClass\->getAttributeAccess("$mockObject"); \& print "breaky\en" if(grep {$_[0] eq \*(Aqstore\*(Aq} @accesses); .Ve .PP A second argument can be supplied which corresponds to the order that the access took place. .SS "noTracking" .IX Subsection "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. .PP .Vb 1 \& $mockClass\->noTracking(); # no more tracking of methodcalls, constructor\-calls, attribute\-accesses .Ve .SS "tracking" .IX Subsection "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. .PP .Vb 1 \& $mockClass\->tracking(); # now tracking is back on. .Ve .SS "constructor" .IX Subsection "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. .PP .Vb 3 \& $mockClass\->constructor(\*(Aqcreate\*(Aq); # change from \*(Aqnew\*(Aq. \& $mockClass\->defaultConstructor(); # installs \*(Aqcreate\*(Aq. \& my $mockObject = MockClass\->create(); # calls \*(Aqcreate\*(Aq on mocked class. .Ve .SS "inheritFrom" .IX Subsection "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. .SH "TODO" .IX Header "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.) .SH "SEE ALSO" .IX Header "SEE ALSO" .IP "Alternatives: Test::MockObject, Test::MockMethod" 4 .IX Item "Alternatives: Test::MockObject, Test::MockMethod" .PD 0 .IP "Testing systems: Test::Simple, Test::More, Test::Builder, Test::Harness" 4 .IX Item "Testing systems: Test::Simple, Test::More, Test::Builder, Test::Harness" .IP "xUnit testing: Test::SimpleUnit, Test::Unit, Test::Class" 4 .IX Item "xUnit testing: Test::SimpleUnit, Test::Unit, Test::Class" .PD .SH "AUTHOR" .IX Header "AUTHOR" Jeremiah Jordan .PP 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. .PP Copyright (c) 2002, 2003, 2004, 2005 perl Reason, \s-1LLC\s0. All Rights Reserved. .PP 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 \s-1GPL\s0.