This document discusses using data factories to generate test data in Perl. It shows how to:
1. Construct a test fixture from a YAML file to populate a database with sample data.
2. Create a factory method that generates sample records on demand with random or specified field values.
3. Configure a data factory object to connect to a database and define the factory method for generating rows in a specific table.
15. use Test::More;
my $data = DBIx::Sample->create(
id => 1,
title => 'entry1',
);
my $data2 = DBIx::Sample->create(
id => 2,
title => 'entry2',
);
# add test ...
28. $factory_maker->create_factory_method(
method => 'create_sample',
table => 'sample',
auto_inserted_columns => {
id => {
type => 'Int',
size => 10,
},
title => {
type => 'Str',
size => 20,
},
},
);
29. my $values = $factory_maker->create_sample;
warn $values->{id};
# +-----------+----------------------+------+
# | id | title | body |
# +-----------+----------------------+------+
# | 452882908 | E54521Hpjkp9Wv1i9Rkb | NULL |
# +-----------+----------------------+------+
30. my $values = $factory_maker->create_sample(
title => 'title',
body => 'body',
);
# +------------+-------+------+
# | id | title | body |
# +------------+-------+------+
# | 3931487566 | title | body |
# +------------+-------+------+
31.
32.
33. $factory_maker->create_factory_method(
method => 'create_sample',
table => 'sample',
auto_inserted_columns => {
id => sub { int rand(1000000000) },
title => {
type => 'Str',
size => 20,
},
},
);