Chapter 2. Writing Tests

Perl has a rich vocabulary, but you can accomplish many things using only a fraction of the power available. In the same way, Perl has an ever-increasing number of testing modules and best practices built around the simple ok() function described in Chapter 1.

The labs in this chapter guide you through the advanced features of Test::More and other commonly used testing modules. You’ll learn how to control which tests run and why, how to compare expected and received data effectively, and how to test exceptional conditions. These are crucial techniques that provide the building blocks for writing comprehensive test suites.

Skipping Tests

Some tests should run only under certain conditions. For example, a network test to an external service makes sense only if an Internet connection is available, or an OS-specific test may run only on a certain platform. This lab shows how to skip tests that you know will never pass.

How do I do that?

Suppose that you’re writing an English-to-Dutch translation program. The Phrase class stores some text and provides a constructor, an accessor, and an as_dutch() method that returns the text translated to Dutch.

Save the following code as Phrase.pm:

 package Phrase; use strict; sub new { my ( $class, $text ) = @_; bless \$text, $class; } sub text { my $self = shift; return $$self; } sub as_dutch { my $self = shift; require WWW::Babelfish; return WWW::Babelfish->new->translate( source => 'English', destination => 'Dutch', text => $self->text(), ...

Get Perl Testing: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.