Search Unity

Unit Testing: Spying on Unity's Own Static Functions

Discussion in 'Scripting' started by Eraph, Jan 5, 2019.

  1. Eraph

    Eraph

    Joined:
    Aug 15, 2015
    Posts:
    45
    I've been getting into unit testing in a big way through my day job, and I'm getting the hang of applying it to Unity. One thing I can't find anything about is latching on to Unity's own static functions. The function I'm looking at currently is
    Random.Range

    I would like to do two things with this function in my test.
    • I want to tell it to spit out a specific series of values for each time it is called (e.g. I call it five times, and I want the output to consistently be 4, 5, 1, 3, 2).
    • I want to know that Random.Range was called five times, and bonus points if I can confirm that it was called with a particular set of arguments.
    I can fake the first requirement by specifying a seed before calling, but I'd really like to know if there is a better way.

    I'm using NUnit and NSubstitute.
     
  2. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    6,609
  3. Eraph

    Eraph

    Joined:
    Aug 15, 2015
    Posts:
    45
    Thanks Peter77, I've been using Unity's built-in test functionality.
    I was hoping there would be a better way to handle Random functionality. The example here describes almost what I want to do (on the same function as it happens), but solves this by abstracting the functionality of Random into its own service - something I want to avoid doing because it seems excessive, given it won't provide any more functionality, and would require discipline in using the service rather than just typing in Random.Range.