O'Reilly logo

Perl Testing: A Developer's Notebook by Chromatic, Ian Langworth

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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(), ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required