简体   繁体   English

Perl单元测试模拟

[英]Perl Unit Test Mocking

I am attempting write a unit test in Perl by mocking. 我试图通过模拟在Perl中编写单元测试。 Its my first attempt at mocking. 这是我第一次嘲笑。

Method is defined in MyConnect.pm 方法在MyConnect.pm中定义

sub connect_attempt {
my ($a, $b, $c) = @_; 
// some calculation with $c
$status = connect( $a, $b );
return status;
}

connect is subroutine defined in Socket module. connect是在Socket模块中定义的子例程。 I need to test two scenario 我需要测试两种情况

1) Connection successful - To test this I am planning to return a new mock object or string 1)连接成功-为了测试这一点,我打算返回一个新的模拟对象或字符串
2) Connection unsuccessful - Status will remain undefined 2)连接失败-状态将保持不确定

MyConnect.t MyConnect.t

use MyConnect;
use Socket;
my $status;
my $mock = Test::MockObject->new();
my $connect_module = Test::MockModule->new('MyConnect');
$connect_module->mock( 'connect_attempt' => sub { return "true"});
my $socket_module = Test::MockModule->new('Socket');
$socket_module->mock( 'connect' => sub { return "true"});
$status = $connect_module->connect_attempt("122", "53", 0);
ok(defined $status, 'Its fine');

I get the below error: 我收到以下错误:

Cant locate object method "connect_attempt" via package "Test::MockModule" at t/MyConnect.t line 21.
#Looks like your test exited with 9 before it could output anything.
Dubious, test returned 9 (wstat 2304, 0x900)`
Line 21 is the call `$status = connect_attempt("122", "53", 0);

As per my understanding, I have created MockModule for my Module(MyConnect) and Socket module since I will invoking connect subroutine from it. 根据我的理解,我已经为我的Module(MyConnect)和Socket模块创建了MockModule,因为我将从中调用connect子例程。 I have set the response from both subroutines to be true. 我已将两个子例程的响应设置为true。 I should be expecting $status to true as well. 我应该期望$ status也为true。

Can someone please explain where I am going wrong. 有人可以解释我要去哪里了。 This is my first unit test with mocking. 这是我的第一个模拟单元测试。 I may have misunderstood certain concept. 我可能误解了某些概念。

Thanks 谢谢

I believe this is because you're using the object oriented usage of the module, but your original module isn't OO. 我相信这是因为您使用的是模块的面向对象用法,但是原始模块不是OO。

Change: 更改:

$status = $connect_module->connect_attempt("122", "53", 0);

...to: ...至:

$status = MyConnect::connect_attempt("122", "53", 0);

...or, change your MyConnect to be OO: ...或者将MyConnect更改为OO:

package MyConnect;

sub new {
    return bless {}, shift;
}

sub connect_attempt {
    my ($a, $b, $c) = @_;
    $status = connect( $a, $b );
    return status;
}
1;

...then change this: ...然后更改此:

$status = $connect_module->connect_attempt("122", "53", 0);

...to this: ...对此:

my $mocked_myconnect = MyConnect->new;
$status = $mocked_myconnect->connect_attempt("122", "53", 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM