I have created an error object from an error hash and I'm trying to create unit tests that check the objects contain all the correct keys.
ErrorLibrary.pm
use constant {
CABLING_ERROR => {
errorCode => 561,
message => "cabling is not correct at T1",
tt => { template => 'disabled'},
fatal => 1,
link =>'http://www.e-solution.com/CABLING_ERROR',
},
};
Error.pm - new subroutine. (Takes error hash as arg & creates a new error object)
package ASC::Builder:Error;
sub new {
my ($package, $first_param) = (shift, shift);
if (ref $first_param eq 'HASH') {
my %params = @_;
return bless { message => $first_param->{message}, %params}, $package;
}
else {
my %params = @_;
return bless {message => $first_param, %params}, $package;
}
}
I'm not sure what I should be testing as my expected output. The specific message key in the hash or an Error object itself. I've been trying to test if a certain key of the hash is contained in the error object, but I don't think I'm going about it the right way. Anyway here is what I've been messing around with:
error_test.t
my $error = CABLING_ERROR;
#is(ref $error, 'HASH', 'error is a hashref');
my $error_in = ASC::Builder::Error->new($error);
my $exp_out_A = ($error->{message}); # is this the right expected output????
is(ref $error_in eq ASC::Builder::Error, 'It is an Error object'); #seen something like this online
#is(defined $error->{errorCode}, 1, "Error object contains key errorCode"); #these only test that the error hash contains these keys
#is(defined $error->{message}, 1, "Error object contains key message");
is($error_in, $exp_out_A, 'Correct message output');
The test file is a bit messy, just because I've been trying various attempts. I hope all the code is free of syntax errors :). Any help would be much appreciated!
These are the other methods contained in the Error.pm file that I want to be able to access , the way I am accessing the error message from the hash. I am not sure if I they are correct, but I think they are pretty close.
sub tt {
my $self = shift;
return $self->{tt} || {$_[0]->{tt} };
}
sub code {
my $self = shift;
return $self->{code} || {$_[0]->{code} };
}
sub wiki_page {
my $self = shift;
return $self->{wiki_page} || {$_[0]->{wiki_page} };
}
The or condition in the return is suppose is so the error can be handled id its just a string or error hash.. I'm also not sure if this is correct.
When I run my unit test on for example the tt method I get the hash value returned instead of the value of tt which is 'disabled'.
Here is the unit test I ran on it:
my $error = CABLING_ERROR;
my $error_in = ASC::Builder::Error->new($error);
isa_ok($error_in, 'ASC::Builder::Error');
can_ok( $error_in, 'tt');
is($error_in->tt(), ( $error || $error->{tt} ), 'Returns correct template');