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

I'm wanting to create a test harness using Test::More to test nearly a dozen classes. The problem is that due to the interdependence between classes, substantive tests cannot be written without a number of classes being instantiated at the same time (The classes represent the object model of a database...), so implementing boilerplate code will only be useful as long as I can embed a number of knobs into the interface.

So, what I have dreamed up is to create yet another module which accepts a hash reference as an argument which specifies the class name(s), method(s), & arguments which are then instantiated & connected together -- passing something akin go the following:

{ 'classname_a' => { 'method_a' => [ parameter1, parameter2 ], 'method_b' => [ parameter1 ], 'method_c' => undef }, 'classname_b' => { 'method_a' => undef, 'method_b' => [ parameter1 ] } }
What I haven't resolved is how to decode this structure into the needed syntax. I haven't been able to get past the following:
sub create { my $ref = shift; my @parameters; my @objects; foreach my $classname (keys %$ref) { my $r = new $classname; # instantiate class foreach my $method (keys %{$ref{$classname}}) { for my $parameter (keys %{$ref{$classname}{$method}}) { push @parameters, ${$ref{$classname}{$method}{$paramet +er}}; } $r->$method(@parameters); } push @objects, $r; } return \@objects; }

I'm sure I am not the first to think of trying to take the output from Data::Dumper & recreate the object(s) hierarchy represented.

Any corrections you would suggest for the syntax (or design...) would be greatly appreciated. Thank you very much.

Replies are listed 'Best First'.
Re: creating objects via string representations?
by jsegal (Friar) on Nov 27, 2008 at 07:19 UTC
    If you have the output of Data::Dumper, you can simply eval it to create the object!

    If you have complicated inter-references between the objects, you need to be sure to give the correct options to Data::Dumper (e.g. set $Data::Dumper::Purity = 1) to get the references correct. If you use the 2-argument form for Dumper, it will use the variable names you specify for the objects.

    People (e.g. merlyn) that in certain edge cases Dumper might break references to the same object, inadvertently duplicating it, but in most cases it works fine (and that article is old enough that perhaps this issue has been fixed by now...).


    --JAS
      Any thoughts on the syntax?