简体   繁体   中英

How can I mock a subroutine for Unit testing in Perl?

Here I am giving the pseudocode for for the subroutine which need unit testing to be done.

sub get_detail_team(param1,param2){

   my $dbh   = connect to databasehandle
   my sql    = get_sql_details(param1,param2)
   my $sth   = $dbh->prepare($sql)
       $sth->execute()
   my $result = $sth->fetchall_arrayref();

return get_html_content($result,prama)
}

the get_sql_details() and get_html_content() are also the sub routines which are in the same package. How can we unit test the get_detail_team() function?

I have tried using this Test::Mockmodule but did not get the exact results.

I don't think this is a good candidate for mocking.

First problem is get_detail_team does two things, it gets the data and it formats it. Formatted data is harder to test than data structures. Separating formatting from functionality makes things much easier to test and it makes it easier to add more formatters. One Extract Method refactoring later...

sub get_detail_team_data($param1, $param2) {
   my $dbh   = connect_to_database;
   my $sql   = get_sql_details($param1, $param2);
   my $sth   = $dbh->prepare($sql)
   $sth->execute();
   return $sth->fetchall_arrayref();
}

sub get_detail_team($param1, $param2) {
    my $detail_team = get_detail_team_data($param1, $param2);
    return get_html_content($detail_team);
}

Now we can focus on testing just the data. Looking at get_detail_team_data it's just a thin wrapper around get_sql_details . To test get_sql_details you'd want to get the SQL and see if it fetches the data its supposed to which is what get_detail_team_data does. You might as well focus testing on get_detail_team_data with only basic integration tests of get_sql_details . That leaves the problem of the database connection.

I'm not a fan of so much mocking that all external services have been removed. If you're going to be writing SQL, you need a SQL database to run it against, else you're not really testing the functionality. I'm going to assume the existence of a test database with a schema which matches the production database. Your tests can populate it with whatever data they like and rollback at the end of the script.

Simplest thing to do is to write connect_to_database so it honors a testing environment variable to connect to a test database. Even better is to have an environment variable which controls where the whole system looks for its configuration information that the whole test suite can take advantage of.

get_detail_team is not worth much testing, it's just a thin wrapper. Write basic integration tests for it and focus on testing get_html_content which you can just pass a data structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM