有没有办法在 Raku 中测试私有(private)方法?
我知道理想情况下应该定义针对公共(public)方法的测试,但是有没有办法以“错误的方式”做到这一点? :)
我最初考虑为继承自我想要测试的类的测试定义一个子类并在那里进行测试,但似乎私有(private)方法没有被继承。
然后我看到了'trusts' routine ,但我不想在代码的任何类上引用测试类。
是否有类似通过内省(introspection)改变方法的“私有(private)”属性?
调用/测试私有(private)方法的最佳方法是什么?
最佳答案
这可以使用自省(introspection)来完成。
考虑这是您要测试的类:
class SomeClass {
has Int $!attribute;
method set-value(Int $value) returns Nil {
$!attribute = $value;
return;
}
method get-value returns Int {
return $!attribute;
}
# Private method
method !increase-value-by(Int $extra) returns Nil {
$!attribute += $extra;
return;
}
}
你可以像这样创建一个测试:use Test;
use SomeClass;
plan 3;
my SomeClass $some-class = SomeClass.new;
my Method:D $increase-value = $some-class.^find_private_method: 'increase-value-by';
$some-class.set-value: 1;
$increase-value($some-class, 4);
is $some-class.get-value, 5, '1+4 = 5';
$increase-value($some-class, 5);
is $some-class.get-value, 10, '5+5 = 10';
my SomeClass $a-new-class = SomeClass.new;
$a-new-class.set-value: 0;
$increase-value($a-new-class, -1);
is $a-new-class.get-value, -1, '0+(-1) = -1; The method can be used on a new class';
done-testing;
你首先创建一个类的实例并使用^find_private_method
得到它的私有(private)Method
.然后你可以调用 Method
通过传递一个类的实例作为第一个参数。这个答案有更完整的解释:
How do you access private methods or attributes from outside the type they belong to?
关于在 Raku 中测试私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62974444/