0

I have an existing function that checks if an input variable is defined, and returns true if it is equal to another variable, and returns false otherwise:

sub isVar1Valid {
    my ($self, $var1) = @_;
    my $var2 = "someValue";   
    return $var1 && $var1 eq $var2;
}

I'm writing unit tests for this function, and the expected output I'm looking for is false. In my unit test, I'm actually testing for 0. However, my test is failing because the above method is returning ' ', and that is not equal to 0.

My unit test looks something like.

my $actualOutput = isVar1Valid($input);
is($actualOutput, 0);

Should I be testing for ' ' as an expected output in my unit test instead? Or should I be returning 0 in my main function instead?

This is my first time working with Perl, so any guidance is appreciated.

2
  • I think you mean an empty string (as produced by ''), not a single space (as produced by ' '). The empty string is false, but a space is true. Commented Jun 27, 2019 at 5:06
  • You're right, I did mean it was returning '', which was the value of $var1 for some test cases. Commented Jun 27, 2019 at 17:28

1 Answer 1

4

If $var1 is false, the sub will return the value of $var1.

If $var1 is true, but different than $var2, the sub will return a scalar that contains the integer 0, the floating point number 0 and the empty string.

But I wouldn't check for any of those values explicitly. They're all legit values, and it's too complicated to check for each one.

Instead, you should normalize.

is(isVar1Valid($input) ? 1 : 0, 0);

Better yet, use ok instead of is.

ok(!isVar1Valid($input));

By the way, note that the following construct is a little weird:

$var1 && $var1 eq $var2

The purpose of the first check is probably to avoid an "uninitialized" warning. If so, it would be best to communicate that to the reader by using the following instead:

defined($var1) && $var1 eq $var2

This is important because the second version isn't equivalent to the second if $var2 can be false.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I was missing adding the defined() for my first check. After adding that check, my unit tests are working as expected. :)
That doesn't mean they're correct. You should still apply one of the fixes I proposed. perl -e'use Test::More tests => 1; my $var1 = ""; is(defined($var1) && $var1 eq "someValue", 0)' fails just as badly as perl -e'use Test::More tests => 1; my $var1 = ""; is($var1 && $var1 eq "someValue", 0)'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.