|The stupid question is the question not asked|
Unit Testing CGI Programsby Wally Hartshorn (Friar)
|on Mar 14, 2003 at 20:41 UTC||Need Help??|
Wally Hartshorn has asked for the
wisdom of the Perl Monks concerning the following question:
I'm attempting to Do The Right Thing (tm), i.e. unit test my programs. I've been reading about unit testing, and it sounds like a very good idea -- I'm sold on the concept! Unfortunately, I've been having problems figuring out how to do it. Nearly all of the programming I do involves database and CGI stuff.
Most of the information I've found about Test::Harness, Test::Simple, Test::More, etc, seem to focus on examples like this:
I can understand how to write that kind of test, but I'm having trouble figuring out how to write a test for code that:
My suspicion is that I need to modify my program to make testing easier.
Suppose the original code is like this:
As it is now, I can't figure out how to write a test that would verify that the web page displayed for employee number "12345" is correct. How would I cause $cgi->param("emp_no") to return "12345"? How would I compare the web page to the expected value? When someone changes the format of the web page, the test would break. Etc.
As I thought about it, I realized that testing for the value of the web page would not be Doing The Right Thing. Instead, I should probably have a subroutine that gets the data ready for display, then test that routine instead. In other words, something more like this:
With the above changes, I wouldn't do unit tests of show_record(), on the theory that it is pretty much all presentation code, not logic (although if anyone has suggestions on how to write unit tests for that, I'm interested). Instead, I would just test get_emp_rec().
Does that sound like Doing The Right Thing, or is there some nifty trick out there that I'm missing?