I have been struggling with the
Test::MockObject documentation for some time. However I think I finally got it today. The thing is that just about every class I ever wish to mock is some sort of file handle. I suppose it is too much to ask to expect the natural "print" syntax to work when mocked up, but it does limit the usefulness of the testing. I have an example:
#!perl
use strict;
use warnings;
use FileHandle;
use Test::MockObject::Extends;
my $mock= Test::MockObject::Extends->new(FileHandle->new);
$mock->set_false( 'print' );
$mock->fake_new('FileHandle');
my $a = FileHandle->new;
$a->open(">K") or die "could not open";
print {$a} "hello" or die "I expect to die here";
$a->print("hello") or die "I expect to be dead before we get to this p
+oint";
When it runs on my system the output is "I expect to be dead before we get to this point at print.t line 15." and the file "K" says "hello".
Edit:I have put together a more basic example.
#!perl
use strict;
use warnings;
package A;
sub new {
my $class = shift;
return bless {}, $class;
}
sub whoami {
my $self = shift;
return "I am an A.\n";
}
sub sayhi {
my $self = shift;
return "Hi!\n";
}
package main;
my $a = A->new;
print $a->whoami;
print $a->sayhi;
use Test::MockObject::Extends;
$a = Test::MockObject::Extends->new($a);
$a->mock('sayhi', sub {return "Nope. Won't say 'Hi!'.\n";});
my $a2 = A->new;
print $a2->whoami;
print $a2->sayhi;
$a->fake_new('A');
my $a3 = A->new;
print $a3->whoami;
print $a3->sayhi;
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.