Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Unit tests with MockObjects

by rovingeyes (Sexton)
on Feb 16, 2010 at 21:07 UTC ( [id://823552]=perlquestion: print w/replies, xml ) Need Help??

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

I recently contributed a module to CPAN http://search.cpan.org/~aivaturi/VMware-LabManager-0.01/lib/VMware/LabManager.pm and I need some help to figure out how to effectively write my unit tests. Since my module depends on an external SOAP service, I think Test::MockObjects would be useful in creating the unit tests (by mocking the SOAP service). But, I am not totally sure & hence my question here. For e.g. if want to create a test for deploy_config method, I need to interact with the external SOAP service, which accepts certain SOAP calls & returns some XML formatted data. This method makes multiple calls to the SOAP service. So by using Test::MockObject, do I register all those SOAP service methods? And since my module uses SOAP::Lite, do I have to mock SOAP::Lite too? Also if there are other modules I should be aware of that will help do the same, please chime in.

Replies are listed 'Best First'.
Re: Unit tests with MockObjects
by GrandFather (Saint) on Feb 16, 2010 at 22:18 UTC

    You only need to mock the members of the SOAP::Lite interface that you are actually using. Consider:

    use strict; use warnings; use Test::MockObject; use Test::More; my $mockSOAP = Test::MockObject->new(); $mockSOAP->fake_module('SOAP::Lite', new => sub {SOAP_new ($mockSOAP, +@_)},); $mockSOAP->mock(soapversion => \&SOAP_soapversion); use_ok('SOAP::Lite'); my $client = SOAP::Lite->new(proxy => 'blah'); is($client->soapversion(), 1.2, 'Version ok'); eval {$client->soapversion(1.3)}; my $result = $@; is($result, "Can't set SOAP version to 1.3\n", 'Bad version rejected') +; done_testing(); sub SOAP_new { my ($mock, $class, %params) = @_; $params{version} ||= 1.2; $mock->{newParams} = \%params; $mock->{newClass} = $class; return $mock; } sub SOAP_soapversion { my ($self, $version) = @_; die "Can't set SOAP version to $version\n" if defined $version && $version != 1.2 && $version != 1.1; $self->{newParams}{version} = $version if defined $version; return $self->{newParams}{version}; }

    Prints:

    ok 1 - use SOAP::Lite; ok 2 - Version ok ok 3 - Bad version rejected 1..3

    True laziness is hard work
      Thanks, that example really helped.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://823552]
Approved by biohisham
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (7)
As of 2024-04-19 09:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found