How to mock an imported subroutine when unit-testing a module

ⅰ亾dé卋堺 提交于 2021-01-27 20:29:26

问题


Consider a module which exports a subroutine that connects to the Internet and returns a result:

unit module A;

sub download is export {
     "result from internet"  # Not the actual implementation, obviously.
}

And another module which imports and calls that subroutine:

use A;  # imports &download into this lexical scope
unit module B;

sub do-something is export {
     download().uc ~ "!!"   # Does something which involves calling &download
}

Now I'd like to write unit tests for module B.
But I don't want the tests to actually connect to the Internet; I'd like them to use a mock version of subroutine download that is controlled by my test script:

use Test;
plan 2;

use B;

my $mock-result;
my &mock-download = -> { $mock-result }

# ...Here goes magic code that installs &mock-download
# as &download in B's lexical scope...

$mock-result = "fake result";
is do-something(), "FAKE RESULT!!", "do-something works - 1";

$mock-result = "foobar";
is do-something(), "FOOBAR!!", "do-something works - 2";

The problem is the missing magic code to override sub download...

In Perl 5, I think this could be achieved pretty easily using glob assignment, or even nicer with the help of Sub::Override or Test::MockModule.

But in Perl 6, the lexical scope of module B closes when it has finished compiling, and can thus no longer be modified by the time the test script is run (correct me if I'm wrong). So this approach doesn't seem possible.

How would one solve this task in Perl 6, then?
I.e. how would one write unit tests for B::do-something, without letting it call the real A::download?


回答1:


The simplest approach might be to use wrap which is described in https://docs.perl6.org/language/functions#Routines but a prerequisite for that is the use soft; pragma which prevents inlining. You'd need to use soft; in module A:

unit module A;
use soft;

sub download is export {
    "result from internet";
}

Module B:

unit module B;
use A;

sub do-something is export {
    download.uc ~ "!!";
}

And the test script:

use Test;
use A;
use B;

&download.wrap({
    "mock result";
});

is do-something, "MOCK RESULT!!", "mock a 'use'd sub";
# ok 1 - mock a 'use'd sub


来源:https://stackoverflow.com/questions/42645801/how-to-mock-an-imported-subroutine-when-unit-testing-a-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!