Unit Testing Algorithms That Include Random Numbers

I write code about fractals and random places generation. In particular, I am using the Diamond-Square algorithm at the moment. For those of you who don't know, it basically gets the average of four values ​​and adds a random number to each step. How will I test the result? Should I use a known seed and manually calculate the average value plus a random value, or what? Should I instead calculate the result in the code using random numbers? Or is there another way? In addition, some people thought about the reverse process (aka TDD, writing tests before the code) would be very grateful).

+4
source share
2 answers

You can use a mocking structure to mock your random number generator. This way you remove randomness from your result and you can test your code with a static set of predefined test cases.

In all cases, you are not testing the generation of random numbers, but the calculations you do. And if you have an error, you really need to know the random numbers used to reproduce the error.

+8
source

Just select the seed and number for some iteration (just like how many times you call this PRNG before actually using the values ​​from it) and use the same data (seed and iteration) in your main code and in unit tests. This data can be in the configuration file , which can be accessed by the main code and unit tests.

+1
source

Source: https://habr.com/ru/post/1439585/


All Articles