Unit Test con Test::More y Test::MockObject
El módulo Test::More es un módulo para hacer unit test en Perl y Test::MockObject es un módulo que permite hacer mocking en forma fácil.
Ejemplo de un simple UnitTest
A continuación un simple ejemplo de un unit test con Test::More (usando la estructura de clase de Moose).Clase a probar:
#File: Person.pm
package Person;
use Moose;
use strict;
use warnings;
use namespace::autoclean;
has '_firstName' => (
is => 'rw',
isa => 'Str',
required => 1,
reader => 'getFirstName',
writer => 'setFirstName',
);
has '_secondName' => (
is => 'rw',
isa => 'Str',
required => 1,
reader => 'getSecondName',
writer => 'setSecondName',
);
sub getFullName{
my ( $self ) = @_;
my $full_name = join ' ' => $self->getFirstName(), $self->getSecondName();
return $full_name;
}
no Moose;
__PACKAGE__->meta->make_immutable;
1;
Unit Test:
#File: PersonTest.t
package PersonTest;
use Moose;
use Test::More tests => 3; #Cantidad de test
use Test::MockObject; #uso de mocking
use strict;
use warnings;
use namespace::autoclean;
use Person; #Clase a probar
#Primer test
subtest 'classTest' => sub {
plan tests => 2; #Cantidad de evaluaciones (aserciones) de test
require_ok( 'Person' ); #Comprueba que esté el módulo
my $persona = Person->new(_firstName=>"", _secondName=>"",);
isa_ok ($persona, 'Person'); #Comprueba si es la clase correcta
};
#Segundo test
subtest 'getFullName' => sub {
plan tests => 3; #Cantidad de evaluaciones (aserciones) de test
my $persona = Person->new(_firstName=>"Diego", _secondName=>"Maradona",);
is($persona->getFullName(),"Diego Maradona",'Full name is right');
isnt ($persona->getFullName(), "Other name", "Bad full name!");
ok( length $persona->getFirstName() == 5, 'First Name length is ok!' );
};
#Tercer test
subtest 'getFullName_Using_Mock' => sub {
plan tests => 1;
my $mockPerson = Test::MockObject->new();
$mockPerson->mock( 'getFullName',
sub { 'Ejemplo' } ); #Mocking de la clase Person
is( $mockPerson->getFullName,"Ejenplo",'Full name is ok with mocking');
};
no Moose;
__PACKAGE__->meta->make_immutable;
1;
Resultado de la corrida del test:
1..3
1..2
ok 1 - require Person;
ok 2 - The object isa Person
ok 1 - classTest
1..3
ok 1 - Full name is right
ok 2 - Bad full name!
ok 3 - First Name length is ok!
ok 2 - getFullName
1..1
ok 1 - Full name is ok with mocking
ok 3 - getFullName_Using_Mock
Referencias:
-Test::More doc.
-Test::More wikipedia.
-Test::More Tutorial.
-Test::MockObject doc.
No hay comentarios:
Publicar un comentario