Я пытаюсь провести модульное тестирование моего модуля Importer::Git
, который использует Git.pm
из CPAN, и я хотел бы посмеяться над вызовами Git::command
, Git::repository
и Git::command_oneline
и т. Д., Чтобы фактически не изменить мою файловую систему.Я пытался сделать это с помощью Test :: MockObject, но, похоже, я еще не полностью понял внутреннюю работу ...
Пример:
package Importer::Git
sub create_repository {
my ( $rc, $repo );
$rc = Git::command_oneline( 'init', $self->targetdir . "/" . $self->name );
$repo = Git->repository( Directory => $self->targetdir . "/" . $self->name );
$rc = $repo->command( 'config', 'user.name', $self->git_import_user->{ name } );
$self->_repo( $repo );
return $repo;
}
Testcase:
use Import::Git;
use Test::More tests => 1; # last test to print
use Test::Exception;
use Test::MockObject;
# pretend to have loaded the Git Module.
$INC{'Git.pm'} = 1;
my $git = Test::MockObject->new();
$git->fake_module('Git', repository => sub { $git } );
$git->set_true( qw(command command_oneline) );
$repo = Import::Git->init();
$repo->targetdir('./');
$repo->name('testrepo');
$repo->git_import_user({ name => 'test', email => 'test@test.com', push_default => 'testpush' });
$repo->create_repository();
Но, похоже, он не заменяет рассматриваемый объект git, так как этот тест дает сбой с сообщениями самого модуля Git.pm.
error: Malformed value for push.default: testpush
error: Must be one of nothing, matching, simple, upstream or current.
fatal: bad config variable 'push.default' in file '/home/.../testrepo/.git/config' at line 10
init .//testrepo: command returned error: 128
Я полагаю, в этих двух строках из Importer:: Git, это не заменяет $ repo
$repo = Git->repository( Directory => $self->targetdir . "/" . $self->name );
$rc = $repo->command( 'config', 'user.name', $self->git_import_user->{ name } );
Так как бы я это правильно высмеял?Я бы хотел, чтобы $repo->command
звонки просто возвращали 1.
ОБНОВЛЕНИЕ:
Дейвс догадался, что это правильно.Исправление кода для этого решило это:
use Test::More tests => 1; # last test to print
use Test::Exception;
use Test::MockObject;
my $git;
BEGIN {
# pretend to have loaded the Git Module.
$DB::single=1;
$INC{'Git.pm'} = 1;
$git = Test::MockObject->new();
$git->fake_module('Git', repository => sub { $git } );
$git->set_true( qw(command command_oneline) );
}
use Import::Git;
my $real_repo = Import::Git->init();
$real_repo->targetdir('./');
$real_repo->name('testrepo');
$real_repo->git_import_user({ name => 'test', email => 'test@test.com', push_default => 'testpush' });
$real_repo->create_repository();