I'd like to inject a RandomNumberGenerator
to my class in order to write unit tests. However, it seems that the methods that receive a random number generator only work with concrete types.
Which means that
var rng: RandomNumberGenerator = SystemRandomNumberGenerator()
Bool.random(using: &rng)
does not compile, with the error:
In argument type
inout RandomNumberGenerator
,RandomNumberGenerator
does not conform to expected typeRandomNumberGenerator
but
var rng = SystemRandomNumberGenerator()
Bool.random(using: &rng)
does.
The trouble with that is that I'd like to use the default random number generator when running my app, and use a custom random number generator that i control for testing. What is the general approach to controlling randomness in order to make testable code in Swift?