Unit Testing with functions that return random results

后端 未结 11 1937
太阳男子
太阳男子 2020-12-05 01:25

I don\'t think that this is specific to a language or framework, but I am using xUnit.net and C#.

I have a function that returns a random date in a certain range. I

11条回答
  •  再見小時候
    2020-12-05 01:56

    I would recommend overriding the random function. I am unit testing in PHP so I write this code:

    // If we are unit testing, then...
    if (defined('UNIT_TESTING') && UNIT_TESTING)
    {
       // ...make our my_rand() function deterministic to aid testing.
       function my_rand($min, $max)
       {
          return $GLOBALS['random_table'][$min][$max];
       }
    }
    else
    {
       // ...else make our my_rand() function truly random.
       function my_rand($min = 0, $max = PHP_INT_MAX)
       {
          if ($max === PHP_INT_MAX)
          {
             $max = getrandmax();
          }
          return rand($min, $max);
       }
    }
    

    I then set the random_table as I require it per test.

    Testing the true randomness of a random function is a separate test altogether. I would avoid testing the randomness in unit tests and would instead do separate tests and google the true randomness of the random function in the programming language you are using. Non-deterministic tests (if any at all) should be left out of unit tests. Maybe have a separate suite for those tests, that requires human input or much longer running times to minimise the chances of a fail that is really a pass.

提交回复
热议问题