How do you use subtesting and table-driven tests with a short example?

In Perl, subtesting allows you to group tests together in a single test block, making it easier to see which tests are related. Table-driven tests, on the other hand, streamline your tests by running them based on data from a hash or array. Here's a short example demonstrating both techniques.


use Test::More;

# Start a test plan, with a total of 3 tests
use Test::More tests => 3;

# Example of subtesting
subtest 'Testing sum function' => sub {
    is(sum(1, 2), 3, '1 + 2 should equal 3');
    is(sum(-1, 1), 0, '(-1) + 1 should equal 0');
};

# Example of table-driven tests
my @tests = (
    [1, 2, 3],
    [-1, 1, 0],
    [5, 5, 10]
);

foreach my $test (@tests) {
    my ($a, $b, $expected) = @$test;
    is(sum($a, $b), $expected, "$a + $b should equal $expected");
}

sub sum {
    my ($x, $y) = @_;
    return $x + $y;
}
    

Perl subtests table-driven tests testing framework Test::More