Agile, test-driven development

It All Started with a Test

Article from Issue 154/2013
Author(s):

Test-driven development with a full-coverage regression test suite as a useful side effect promises code with fewer errors. Mike "Perlmeister" Schilli enters the same path of agility and encounters a really useful new CPAN module.

A few weeks ago, my employer sent me to a course about test-driven development (TDD) and agile methods, and to implement my newly gained knowledge practically, I am dedicating today's Perl snapshot to this principle.

Fast and flexible developers typically set off immediately without paying attention to details. They always write a test first before they get down to implementing a function. The test suite thus grows automatically with tests relevant to system functions. They clean up dirty code by refactoring later; this is possible without any risk thanks to the safety net provided by the test suite.

Nothing but Errors – and Rightly So

The tests developed before writing a function will fail, of course, because the desired feature either does not exist or is only partially or incorrectly implemented at first. When the code arrives later on, the test suite passes and turns to green; development environments such as Eclipse actually visualize it this way.

For example, to write a User.pm class for a login system that later supports methods such as login(), TDD disciples first create a test case. It checks whether the desired class can actually be instantiated. Listing 1 shows the test file for simple test cases, Basic.pm. It is located in the directory t and uses the brand new CPAN Test::Class::Moose module from CPAN. The latter runs all methods with the test_ prefix and the test utility routines they invoke.

Listing 1

Basic.pm

01 package TestsFor::User;
02 use Test::Class::Moose;
03
04 sub test_constructor {
05   can_ok 'User', 'new';
06 }
07
08 1;

Listing 1 [1] defines test_constructor() and runs the command

can_ok 'User', 'new';

from the Test::More module in it. Thus, test_constructor() verifies whether the User class is capable of calling its constructor new.

Listing 2 shows a script for running the test suite. At first, it draws in the Load module, which loads all Perl modules with the .pm suffix that exist in the specified subdirectories (. and t). The runtests() method then executes all test_* routines found in these modules. In this phase of the project, the User class does not yet exist, and the test case in test_constructor() thus fails (Figure 1).

Listing 2

runtests

01 #!/usr/local/bin/perl -w
02 use Test::Class::Moose::Load
03   qw(t .);
04 Test::Class::Moose->new
05   ->runtests;
Figure 1: Initially, the test suite raises the alarm because nobody has written the User class yet.

A Sense of Achievement

The test-driven developer naturally expected this outcome and now does everything possible to add code until the test suite completes without error. Because the class does not exist, the developer creates a new User.pm file and then adds the following content:

package User;
use Moose;
1;

Old hands like your very own Perlmeister might rub their eyes in disbelief at this, because the User package does not define a new() constructor that welds an object hash $self onto a package using bless(). The Moose [2] CPAN module does all of this behind the scenes, so every packet that Moose looks at automatically owns a new() constructor.

A new run of the test suite using ./runtests returns these promising results:

<[...]>
ok 1 - TestsFor::User

The suite therefore finds the new .pm file, the class it contains, and the new() constructor.

Once More into the Agile Fray

Green light – the signal for TDD developers to add a new feature. The User object needs methods to set and query the user's email address. A developer working conventionally would probably immediately start typing the seemingly simple code. Not so TDD followers; they first write a test that again fails.

Listing 3 defines the test_accessors() method, which the test module later also finds and calls due to the prefix. It creates a new object of the User type and passes the parameter pair email => 'a@b.com' to the constructor. One line later, the erstwhile undefined accessor retrieves the email string set by the constructor, and the is function from the Test::More module compares the value with the one set previously. If the contents match, is writes the ok string to the TAP output of the test suite. The suite will recognize this as a successfully executed test case.

Listing 3

Accessors.pm

01 package TestsFor::User;
02 use Test::Class::Moose;
03
04 sub test_accessors {
05
06  my $email1 = 'a@b.com';
07  my $email2 = 'c@d.com';
08
09  my $user =
10    User->new(
11   email => $email1,);
12  is $user->email(), $email1;
13
14  # Setter
15  $user->email($email2);
16  is $user->email(), $email2;
17 }
18
19 1;

This test is followed by a test of the setter, which uses the email() method to set a new value for the user's email address and then runs the accessor (also email() but without an argument) to retrieve the stored value again and compare it with the original. But the User.pm class still does not have the necessary code; the new test therefore fails immediately.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Perl: Regression Tests

    With a test suite, you can fix bugs and add new features without ruining the existing codebase.

  • Calculating Probability

    To tackle mathematical problems with conditional probabilities, math buffs rely on Bayes' formula or discrete distributions, generated by short Perl scripts.

  • Perl: Web Regression Test

    Testing complex web applications does not necessarily mean investing in expensive, proprietary tools such as Test Director or Silk Performer. Selenium is for free; it can remotely control any major browser, and it is programmable in Perl.

  • Perl – Distro Update Analysis

    A Perl script calls various plugins that sniff around on FTP and HTTP servers run by the major Linux distributions to discover when Fedora, Debian, and other distros update their packages.

  • Perl: Cucumber

    The Cucumber test framework helps developers and product departments jointly formulate test cases, not as program code, but in plain English. The initially skeptical Perlmeister has acquired a taste for this.

comments powered by Disqus

Direct Download

Read full article as PDF:

Price $2.95

News

njobs Europe
What:
Where:
Country:
Njobs Netherlands Njobs Deutschland Njobs United Kingdom Njobs Italia Njobs France Njobs Espana Njobs Poland
Njobs Austria Njobs Denmark Njobs Belgium Njobs Czech Republic Njobs Mexico Njobs India Njobs Colombia