I have a Perl module that I have declared some constants:
use constant BASE_PATH => "/data/monitor/";
In live operation the constant will never change but I wish to be able to modify it in my unit tests, e.g. to set it to ~/project/testdata/
. Is there a way do do this without having to use global mutable variables?
Could I possibly use Test::MockObject
on the constant
?
Every developer wants to promote code reuse. Generally, reuse is a good thing. It makes for more maintainable and more correct code.
Constants may be lists of more (or less) than one value. A constant with no values evaluates to undef in scalar context. Note that constants with more than one value do not return their last value in scalar context as one might expect. They currently return the number of values, but this may change in the future.
When using constants they are implemented as constant functions behaving something like:
use subs 'BASE_PATH';
sub BASE_PATH () {"/data/monitor/"}
Any uses of BASE_PATH in the program are inlined and so can't be modified.
To achieve similar you could manually use the subs pragma (to make BASE_PATH behave as a built in function) and declare BASE_PATH as a standard function:
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";
Although why you would want to do this I'm not too sure.
Tests often reveal inflexibility in the design. This is one of those times. That constant shouldn't be constant.
If you're doing it for performance reasons I'm willing to bet hard currency that it doesn't make any difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With