water has asked for the wisdom of the Perl Monks concerning the following question:

Hi -- I often use the feature of a Class::DBI object that in string context it returns the primary key.
# untested sample code my $a = Foo->retrieve(999); # $a is CDBI object &some_sub('' . $a); # cast object back to scalar, here 999
If I wanted to mock a Foo object using the most excellent Test::MockObject approach, how would I set it up to control the stringification?
# untested sample code my $mocka = Test::MockObject->new; $mocka->set_isa('Foo'); # ??? how to overload stringification # such that I can mock the result of # '' . $mocka # ???
Thanks wise and friendly monks!

water

Replies are listed 'Best First'.
Re: Mocking Class::DBI stringification
by water (Deacon) on Jul 10, 2005 at 21:09 UTC
    Below's an example of subclassing T:MO to achieve this...

    My question, I guess: is there a better way to achieve this w/o all the multiple subclassing? (Would have to do this for each Mock Class, for if just overloaded '""' in Test:MockObject itself, all the mocked classes would stringify the same way, which isn't what I need.

    use strict; use warnings FATAL => 'all'; use Test::MockObject; use Test::More tests => 2; my $id = -1; package MockFoo; use base qw(Test::MockObject); use overload '""' => sub {return $id}; package main; my $c = MockFoo->new; $c->set_isa('Foo'); $c->set_bound('id', \$id); is($c->id, -1, 'accessor'); is('' . $c, -1, 'stringify');
Re: Mocking Class::DBI stringification
by GrandFather (Saint) on Jul 10, 2005 at 21:11 UTC

    I don't know CDBI so you need to help me a little. What does $a look like when you data::dumper it? If $a is scalar then it will be stringified just by using the concatenation operator. If it is something else then you will get a string, but maybe not the one you expect.


    Perl is Huffman encoded by design.