Is there a way to override the Perl usage constant when testing a device?

I have a Perl module that I declared with some constants:

use constant BASE_PATH => "/data/monitor/";

In real time, the constant will never change, but I want to change it in my unit tests, for example. to install ~ / project / testdata / . Is there a way to do this without having to use "not constants"?

Can I use Test :: MockObject on .pm constant?

+3
source share
4 answers

When using constants, they are implemented as constant functions that behave as:

use subs 'BASE_PATH';
sub BASE_PATH () {"/data/monitor/"}

BASE_PATH .

, ( BASE_PATH ) BASE_PATH :

use subs 'BASE_PATH';
sub BASE_PATH {"/data/monitor/"}

print "BASE_PATH is ".BASE_PATH."\n";

*BASE_PATH = sub {"/new/path"};
print "BASE_PATH is ".BASE_PATH."\n";

, .

+6

. - . .

, , .

+5
package My::Class;

use constant BASE_PATH => "/a/real/value/";

# ..more code here..

1;

:

use My::Class;
*{My::Class::BASE_PATH} = sub { "/a/fake/value" };

# do your tests here...
+2

-, BASE_PATH / , (

*BASE_PATH = sub { ... }

or other things) you have no solution (because when the source module used BASE_PATH as a constant, it really defined the INLINE function, which was, well, built-in when used in other code)

+1
source

Source: https://habr.com/ru/post/1711674/


All Articles