且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更改 $*DISTRO 值以进行测试

更新时间:2023-09-17 19:17:22

详细说明 raiph 的答案:$*DISTRO 中的 * 将其标记为动态变量.您可以在任何范围内重新声明它,从那里调用的代码将看到重新声明的值:

To elaborate on raiph's answer: the * in $*DISTRO marks it as a dynamic variable. You can re-declare it any scope, and code called from there will see the redeclared value:

{
    my $*DISTRO = ...;
    # coded called from here sees the redeclared value
}
# code called from here sees the original value

现在,问题仍然存在,你用什么来代替这些讨厌的...?

Now, the question remains, what do you put in place of these pesky ...?

在最简单的情况下,一个只包含被测代码所需的模拟:

In the simplest case, a mock that just has whatever the code under test needs:

{
    my class Distro { has $.is-win }
    my $*DISTRO = Distro.new( :is-win );
    # call your test code here
}

如果代码需要在 Distro 中添加更多属性,只需将它们添加到模拟 Distro 类中即可.

If the code needs more attributes in Distro, just add them to the mock Distro class.

如果代码需要一个真正的* Distro 对象,出于某种原因,您可以实例化内置对象.构造函数 .new 并没有真正记录在案,但是源代码很明显它期望什么参数一>.

If the code needs a "real* Distro object, for some reason, you can instantiate the built-in one. The constructor .new isn't really documented, but the source code makes it pretty obvious what arguments it expects.