How to mock random.choice in python?
<p>I want <code>choice</code> to return the same value <code>1000</code> every time in my unittest. The following code doesn't work.</p>

<pre><code>import unittest
from random import choice

from mock import mock

def a():
    return choice([1, 2, 3])

class mockobj(object):
    @classmethod
    def choice(cls, li):
        return 1000

class testMock(unittest.TestCase):

    def test1(self):
        with mock.patch('random.choice', mockobj.choice):
            self.assertEqual(a(), 1000)
</code></pre>

<p>The error message is as follows:</p>

<pre><code>Failure
Traceback (most recent call last):
  File "test.py", line 15, in test1
    self.assertEqual(a(), 1000)
AssertionError: 3 != 1000
</code></pre>

<p>How should I modify it to make it work? I'm using python2.7</p>

<p>I don't know what is mockobj from tests but what you can do is.</p>

<pre><code>    @mock.patch('random.choice')
    def test1(self, choice_mock):
        choice_mock.return_value = 1000
        self.assertEqual(a(), 1000)
</code></pre>

python unit-testing mocking