gpt4 book ai didi

perl - DBD::Mock 为存储过程指定输出值

转载 作者:行者123 更新时间:2023-11-28 19:54:08 26 4
gpt4 key购买 nike

我正在尝试使用 DBD::Mock测试使用数据库的代码。到目前为止,正常的 SQL 查询工作得很好,但是我对如何测试调用存储过程的代码有些不知所措。使用 DBD::Mock::Session->new 构造函数的 bound_params 键,我可以指定输入参数,但我似乎找不到设置方法使用 DBI::StatementHandle::bind_param_inout() 绑定(bind)参数的模拟结果。

要提供要测试的代码示例,请查看以下内容:

use DBI;
my $dbh = DBI->connect('dbi:Mock', '', '', { RaiseError => 1, PrintError => 1 });
my $sth = $dbh->prepare(q{
BEGIN
some_stored_proc(i_arg1 => :arg1, o_arg2 => :arg2);
END;
});
my ($arg1, $arg2) = ('foo', 'bar');
$sth->bind_param(':arg1', $arg1);
$sth->bind_param_inout(':arg2', \$arg2, 200);
$sth->execute();
print STDERR "OUTPUT VALUE OF arg2 = $arg2\n";

现在,我想为 arg2 参数使用 'frobnication' 为数据库播种,这样当执行上述代码时,$arg2 变量包含这个字符串,输出是

OUTPUTVALUE OF arg2 = frobnication

最佳答案

这是我最后做的。本质上,主要工作是覆盖 DBD::Mock::st::bind_param_inout 方法。

use DBI;
use DBD::Mock;
use DBD::Mock::st;
use Carp;

# array of values to be bound on each invocation
my @values = qw/frobnication/;
# dummy variable to trick DBD::Mock into thinking it got the same reference for
# bind_param_inout and bound_params (the former is usually not in the control of
# the testing code, hence this hack).
my $dummy = undef;
# keep reference to the original bind_param_inout method
my $bind_param_inout_orig = \&DBD::Mock::st::bind_param_inout;
# override with our mocked version that assigns a value to the reference.
# notice that it does so at the bind_param_inout call, *NOT* the execute call!
local *DBD::Mock::st::bind_param_inout = sub {
my ($self, $param_num, $val, $size) = (shift, shift, shift, shift);
$bind_param_inout_orig->($self, $param_num, \$dummy, $size, @_);
$$val = shift @values or Carp::confess '@values array exhausted!';
};

# set up the mock session
my $dbh = DBI->connect('dbi:Mock:', '', '',
{ RaiseError => 1, PrintError => 1 });
$dbh->{mock_session} = DBD::Mock::Session->new('foo_session' => (
{
statement => qr/BEGIN\n\s*some_stored_proc/,
results => [],
bound_params => ['foo', \$dummy]
}));

# this is the code to be tested

my $sth = $dbh->prepare(q{
BEGIN
some_stored_proc(i_arg1 => :arg1, o_arg2 => :arg2);
END;
});
my ($arg1, $arg2) = ('foo', 'bar');
$sth->bind_param(':arg1', $arg1);
$sth->bind_param_inout(':arg2', \$arg2, 200);
$sth->execute();
print STDERR "OUTPUT VALUE OF arg2 = $arg2\n";

关于perl - DBD::Mock 为存储过程指定输出值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15200873/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com