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 completedThe tests => 5 parameter tells Test::More to expect exactly 5 tests, helping catch incomplete test suites.
Was this helpful?
Related Questions
- How to use Test::Deep for complex data structure comparison?
- How to test Mojolicious applications in Perl?
- How to test HTTP responses with Test::WWW::Mechanize in Perl?
- How to use prove command to run Perl tests?
- How to test database code with Test::mysqld in Perl?
- How to use Test::Fatal for exception testing in Perl?