本文介绍了在Perl中模拟超类调用(使用Test :: MockObject)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一些测试中使用了MockObjects,只是不得不通过调用SUPER类来测试一个函数,而我似乎无法使其正常工作.可以不嘲笑像$ this-> SUPER :: save()这样的通用调用吗?如果是,您该怎么做?

I'm using MockObjects in some of my tests and just had to test a function with a call to a SUPER class and I cannot seem to make it work. Can UNIVERSAL calls like $this->SUPER::save() not be mocked? If yes, how do you do it?

谢谢.

找到了!

使用Test::MockObject

因此,假设您的基本模块为Some::Module,并且您的子例程正在进行$this->SUPER::save调用,请使用

So, let's say your base module it Some::Module, and your subroutine is making a $this->SUPER::save call, use

my $child_class_mockup = Test::MockObject->new();
$child_class_mockup->fake_module(
    'Some::Module',
    save => sub () { return 1; } 
);

让问题待上两天,以便在接受此答案之前获得有关执行此操作的不同方式/库的信息(如果SUPER调用具有SUPER调用?).

Leaving the question open for a couple of days, to get inputs about different ways/libraries of doing this (what if, the SUPER call had a SUPER call?) before accepting this answer.

推荐答案

找出对象的超类的名称(或超类之一,因为Perl具有多重继承),并在超类的包中定义save调用

Find out the name of the object's superclass (or one of the superclasses, since Perl has multiple inheritance), and define the save call in the superclass's package.

例如,如果您有

package MyClass;
use YourClass;
our @ISA = qw(YourClass);   # <-- name of superclass
...
sub foo {
    my $self = shift;
    ...
    $self->SUPER::save();    # <--- want to mock this function in the test
    ...
}

sub save {
    # MyClass version of save method
    ...
}

然后在您的测试脚本中,您会说

then in your test script, you would say

no warnings 'redefine';     # optional, suppresses warning

sub YourClass::save {
    # mock function for $yourClassObj->save, but also
    # a mock function for $myClassObj->SUPER::save
    ...
}

这篇关于在Perl中模拟超类调用(使用Test :: MockObject)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 16:36