Is Perl unit testing only for modules, not programs?

The documents I found on the web and in my book, Perl Testing, either say or suggest that unit testing for Perl is usually done when creating modules.

It's true? Is there no way for unit testing of real programs using Test::More and cousins?

+6
source share
2 answers

Of course, you can test the scripts with Test :: More . This is simply harder because most scripts need to be run as a separate process from which you extract the output, and then check it for the expected output.

This is why modulinos (see chapter 17 in: brian d foy , Mastering Perl , second edition, O'Reilly, 2014). Modulino is a script that can also be used as a module. This makes testing easier, since you can load a module into your test script and then test its functions, just like a regular module.

A key feature of modulino is the following:

 #! /usr/bin/perl package App::MyName; # put it in a package run() unless caller; # Run program unless loaded as a module sub run { ... # your program here } 

The function should not be called run ; you can use main if you are a C programmer. You usually also have additional routines that run calls if necessary.

Then your test scripts can use require "path/to/script" to load your module and implement its functions. Since many scripts include writing output, and it is often easier to print as you go instead of print sub_that_returns_big_string() , you may find Test :: Output useful.

+11
source

This is not the easiest way to test your code, but you can directly test the script. You can run the script with certain parameters using system (or better IPC::Run3 ), capture the output and compare it with the expected result.

But it will be a top-level test. It is hard to say how much of your code caused the problem. Unit tests are used to test individual modules. This makes it easier to view the problem. In addition, testing functions individually is much simpler, because you only need to think about what can happen in a smaller piece of code. The testing method depends on the size of your project. You can, because of what, put everything in one file, but inserting your code into a module (or even splitting it into different modules) will give you advantages in the future: the code may be easier to reuse and test.

0
source

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


All Articles