Skip to content
Advertisement

How to unit test a function that creates a connection object assuming there will not be internet access?

I have a python function that creates a Client object from the aiosnow module, which is an API wrapper for ServiceNow like this:

JavaScript

Assuming I will not have internet connection during unit testing, how or what part am I supposed to make the unit test for, which part am I supposed to mock?

Advertisement

Answer

One approach is just to guarantee that the Client constructor has been called. You can accomplish this with unittest.mock.Mock().assert_called (or some variant of it, like assert_called_with). This will entail mocking the Client class, so that when the test runs and you call the Client constructor, no code from Client actually runs. The mock gets called and then you can make assertions based on what you expected to happen.

This is a correct approach because you and your test don’t care about the inner workings of the Client class. You’re testing your function which is supposed to create a client, not that Client works correctly. By mocking out the Client class, your test simply guarantees that your code instantiated a Client, but doesn’t run any Client code.

Here’s an example:

JavaScript

and here’s the corresponding output:

JavaScript

You can see that "New Foo" did not appear in the output of the test, because the class has been mocked.

You can read more about mocking in the Python docs.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement