ImportError: No module named mock

unittest is a built-in module; mock is an external library (pre-3.3 betas, anyway). After installing mock via pip install, you import it not by using

from unittest.mock import MagicMock

but

from mock import MagicMock

Edit: mock has been included in the unittest module (since Python3.3), and can be imported by import unittest.mock.


If you want to support both, Python 2 and Python 3, you can also use following:

import sys
if sys.version_info >= (3, 3):
    from unittest.mock import MagicMock
else:
    from mock import MagicMock

or, if you don't want to import sys

try:
    from unittest.mock import MagicMock
except ImportError:
    from mock import MagicMock

For Python 2.7:

Install mock:

pip install mock

Then in the test code, use this import:

from mock import patch, MagicMock