Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Common Problems With Mocking

00:00 Mocking is great in a lot of ways, but there are some common problems that may come up when you introduce mocking. Sometimes the intention of mocking is valid, but the actual mock object is not valid, and that leads to test assertions being irrelevant.

00:17 Here are a few common problems with mocking. The first one is changes to object interfaces. Class functions and definitions change all the time, and sometimes when you’re mocking a function, it has a dependency on the name of it.

00:33 So if you change the name of a function and you have a mock that calls that function, the assertion might not be relevant anymore. For example, if you were asserting that a function was not called and you rename that function, the assertion is still going to be True, but you’re actually not really testing anything because that function name changed, that interface changed.

00:57 So changing the name of a function can make your tests irrelevant, and that may not sound dangerous, but it actually is if those are the only tests you have written for that particular functionality.

01:09 Another common problem is changes to external dependencies. This problem is inherent in all mocking situations. If an external dependency changes and you’ve created a mock based on an old version, your tests are going to succeed and it’s going to look great, but when you go to production you will see that there may be issues because if there are any breaking changes to the interface, your tests aren’t going to be able to catch that because you’ve mocked the older version of that dependency.

01:40 So you just need to be careful and stay up-to-date with any changes of dependencies and interfaces that your code relies on. Fortunately, the unittest.mock module offers some solutions to some of these common problems, especially the ones with the object interface changes and misspellings and typos that can occur and lead to irrelevant tests.

02:04 Let’s explore that a little bit more.

Become a Member to join the conversation.