testing beginner

How to use Test::More for basic unit testing

Question

How do I write basic unit tests in Perl using Test::More?

Test::More is the standard testing framework for Perl. Here's a basic example:

use strict;
use warnings;
use Test::More tests => 5;

sub add {
    my ($a, $b) = @_;
    return $a + $b;
}

sub multiply {
    my ($a, $b) = @_;
    return $a * $b;
}

# Run tests
is(add(2, 3), 5, 'Addition works correctly');
is(add(-1, 1), 0, 'Addition with negative numbers');
isnt(add(2, 2), 5, 'Addition returns wrong value');
ok(multiply(3, 4) == 12, 'Multiplication works');
like("hello world", qr/world/, 'Pattern matching test');

print "All tests completed\n";

Output:

ok 1 - Addition works correctly
ok 2 - Addition with negative numbers
ok 3 - Addition returns wrong value
ok 4 - Multiplication works
ok 5 - Pattern matching test
1..5
All tests completed

The tests => 5 parameter tells Test::More to expect exactly 5 tests, helping catch incomplete test suites.

Was this helpful?

Related Questions