• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unit Testing

1. Say I have a function GetUuid, which returns a unique UUID each time it is called. How would I unit test such a function? Would I need to develop a function IsUuid($uuid), which will return a TRUE or FALSE if $uuid is a valid UUID pattern or not? If so, how would I use it in CI's unit testing framework?

2. What is the best practice for unit testing private or protected methods within a class? Do I need to make them public for unit testing? Then make them private or protected again after unit testing. (This is not such a great idea if you have a lot of these private and protected methods.)

[eluser]Pascal Kriete[/eluser]
1. If you use a procedure that can cryptographically be called random (like sha1 hashing another somewhat random thing), you probably only need to verify it manually. There is no easy way to test against a random pattern. Ok, in theory there is, but you need a significantly large sample (and I don't mean 23 either) and a lot of math to create a regression that models the function. And even then you're only extrapolating. (I have managed to sound like a smartass in just three sentences)

2. You should be able to make your protected and private methods specific enough that you can test them as part of an accessible method. Alternatively you could give each class a public testing interface that you later remove again. Something generic like:
function test($private_method_name)
    $args = func_get_args();
    if (count($args) > 1)
        // Remove $private_method_name
        $args = array_slice($args, 1);
    // Call the private function
    return call_user_func_array(array($this, $private_method_name), $args);

Untested, but it should work like this: Pass in the private method name as the first argument, and then any arguments that should be sent to the private function.
// In a class
private function null_var($variable)
    $this->$variable = NULL;
    return 'howdy';
// ....
echo class->test('null_var', 'variablename');  // echos howdy and sets variablename class variable to null

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.