# How to unit test with random values

How do I unit test with random values? I need to ensure that it `gen_age`

returns an integer between 15 and 99, but this code is wrong.

``````import random
import unittest

def gen_age():
# generate integer between 15 and 99
return random.randint(15, 99)

class AgeTest(unittest.TestCase):

def setUp(self):
self.a = gen_age()

def test_choice(self):
element = random.choice(self.a)
self.assertTrue(element in self.a)

def test_sample(self):
for element in random.sample(self.a, 98):
self.assertTrue(element in self.a)

if __name__ == '__main__':
unittest.main()
```

```
+3

source to share

The best way to test similar behavior is to set the seed to a Random object.

The Random package provides the Random class. Random instances have the same methods as a random package; random (), randint (), sample (), ... Additionally, Random accepts a seed. Adding a seed to Random makes it deterministic. For example,

``````from random import Random
random = Random(666)
assert random.randint(0, 1000) == 467  # will never break
```

```

Hence, you would like to test your function as

``````from random import Random
import unittest

random = Random()

def gen_age():
# generate integer between 15 and 99
return random.randint(15, 99)

class AgeTest(unittest.TestCase):

def setUp(self):
global random
random = Random(666)

def test_gen_age(self):
self.assertEqual(gen_age(), 53)

if __name__ == '__main__':
unittest.main()
```

```

Note that if your test is not in the same file, you will need to patch it randomly using `unittest.mock.patch`

. Something like this should work

``````from random import Random
from package.file import gen_age
import unittest

class AgeTest(unittest.TestCase):

def setUp(self):
self.random = Random(666)

@patch('package.file.random')
def test_gen_age(self, random):
random.randint._mock_side_effect = self.random.randint
self.assertEqual(gen_age(), 53)
```

```
+6

source

It should be something like this:

``````def test_GenAge_ReturnIsBetween15And99(self):
self.assertTrue(self.a >=15 and self.a <= 99);
```

```

But you don't really need to check the gen_age function at this time. You are trying to check the python based random generator API, but what is the reason? I do not see.

+1

source

All Articles