Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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
?
–
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.
–
–
–
–
–
Apparently, if your definition of BASE_PATH was used/compiled into another subroutine BEFORE your test does change it (via
*BASE_PATH = sub { ... }
or other stuff) you have no solution (because when the original module used BASE_PATH as a constant, it really defined an INLINE function that was, well, inlined when used in other code)
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.