Test2::V0

2024-06-25 perl Test::More Test2::V0 test unit tests

I really like unit testing in Perl and in fact its was first programming environment where I learned and used the test-driven development. For years, I used Test::More and was quite satisfied with it. You can find numerous of examples of its use on this site, such as in this post about date parsing.

While reading this year’s Perl Advent calendar, I came across an article discussing the evolution of testing modules, specifically Test2::V0. This module is the next generation of testing tools in Perl, build on lessons learned from its predecessors. At first glance, it appears quite similar to Test::More but offers a more polished interface and many useful comparison tools. These enhancements make it easier to write and maintain tests, especially for complex data structures and edge cases.

Here’s an example using Test2::V0

use Test2::V0;

# test loading of a module
use ok 'Test2::V0';

# basic checks
ok 1, 'True test';
ok 0, 'False test', 'Output extra stuff';
is 1, 1, 'Comparison';

# structure comparisons
my $data = { a => 1, b => 2 };
is $data,  { b => 2, a => 1 }, 'Compare structures';
is $data,  { a => 1, b => 3 }, 'Failed comparison of structures';
like 'string', qr/str/, 'Regex comparison';
like $data, { a => 1 }, 'Only check part of structure';

# more advanced checks
is [1, 3, 2], bag { item 1; item 2; item 3; end }, 'set comparison';

done_testing;

In the example above, you can see some of the core features of Test2::V0 in action. The ok function is used for basic true/false checks, while is and like provide more detailed comparisons with better output and what failed. Unlike with Test::More, they also work for structures, including regex matching and partial structure validation. The bag function demonstrates how Test2::V0 can handle unordered lists, ensuring that all expected items are present regardless of order.

You can find the documentation for all advanced checks. This documentation includes comprehensive details on how to leverage the full power of Test2::V0, with examples covering a wide range of testing scenarios. Whether you are verifying simple conditions or complex data interactions, Test2::V0 offers robust tools to enhance your testing suite.