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

Hi --

After an earlier question (Mocking Class::DBI stringification) about Test::MockObject, I pushed on a bit and then encountered (to me) some extremely befuddling behavior.

In the code below, after I reset a variable, $id='apple', the mocking breaks.

Why?

Thanks --

water

use strict; use warnings FATAL => 'all'; use Test::MockObject; use Test::More tests => 7; use Data::Dumper; use UNIVERSAL qw (isa can); package main; my $id = -1; sub return_id {return $id;} package MockFoo; # ! THIS IS THE *WRONG* WAY TO STRINGIFY A T:MO ?? use base qw(Test::MockObject); use overload '""' => \&::return_id; package main; my $c = MockFoo->new; $c->set_isa('Foo'); $c->mock('id', \&::return_id); is($id, -1, 'the bound scalar'); isa_ok($c, 'Foo'); ok ($c->isa('Foo'), 'and c isa foo, maybe'); ok(!isa($c,'Foo'), 'THIS SHOULD WORK (IMHO) but DOESNT, T:MO DOESNT FO +OL UNIVERSAL'); ok(!can($c, 'id'), 'THIS SHOULD WORK (IMHO) but DOESNT, T:MO DOESNT FO +OL UNIVERSAL'); is($c->id, -1, 'mocked accessor'); is($c->id, -1, 'mocked accessor repeated'); is('' . $c, -1, 'stringify'); $id='apple'; is($c->id, 'apple', 'apple: mocked accessor'); is('' . $c, 'apple', 'apple: stringify');

Replies are listed 'Best First'.
Re: Test::MockObject subclassing befuddlement
by Zaxo (Archbishop) on Jul 11, 2005 at 04:33 UTC

    The first test failures I get with your code are #2 and #3, testing that $c is a 'Foo'. It isn't.

    A MockFoo is not a Foo. If perl thought it were, perl would burrow into the Foo namespace for methods and ignore the mocked-up ones.

    I suspect your difficulty with id() comes from the closure behaving unexpectedly, but I can't prove it.

    After Compline,
    Zaxo

      I suspect your difficulty with id() comes from the closure behaving unexpectedly, but I can't prove it.

      Yes, I think you're right, and that's the crux of my problem. Any suggestions?

Re: Test::MockObject subclassing befuddlement
by chromatic (Archbishop) on Jul 12, 2005 at 00:19 UTC

    It's a bug in Test::MockObject. When the stringification of an object changes, T::MO can't find the mocked methods. I have a fix in hand and I'll roll a new release tonight.

    Thanks for the test case!

      Hurrah! Indeed, chromatic, you rock. Highest praise, and thanks.