Unit testing - how do I test a function that returns random output?

后端 未结 6 834
半阙折子戏
半阙折子戏 2020-12-07 01:01

I have a function which takes in two parameters, and returns one or the other 50% of the time.

The unit test for this should determine that both parameters could be

6条回答
  •  被撕碎了的回忆
    2020-12-07 01:09

    Not sure if this is the best way, but I would use a while loop with two flags that I set based on the values I get from the function. I would also use some sort of limit so that the test doesn't go into an infinite loop if the test fails (i.e., doesn't received one of the two values). So:

    int limit = 100;
    int i = 0;
    while(!firstValueReceived && !secondValueReceived && i < limit) {
       int value = randomFunc();
    
       if(!firstValueReceived) {
          firstValueReceived = (value == firstValue);
       }
    
       if(!secondValueReceived) {
          secondValueReceived = (value == secondValue);
       }
       i++;
    }
    
    assertTrue(firstValueReceived && secondValueReceived);
    

    I guess you could use the test hanging as a metric to decide if it failed or not, so you could do away with the limit:

    while(!firstValueReceived && !secondValueReceived) {
       int value = randomFunc();
    
       if(!firstValueReceived) {
          firstValueReceived = (value == firstValue);
       }
    
       if(!secondValueReceived) {
          secondValueReceived = (value == secondValue);
       }
    }
    
    assertTrue(firstValueReceived && secondValueReceived);
    

提交回复
热议问题