0

So let's say I have this bit of code:

import coolObject def doSomething(): x = coolObject() x.coolOperation() 

Now it's a simple enough method, and as you can see we are using an external library(coolObject). In unit tests, I have to create a mock of this object that roughly replicates it. Let's call this mock object coolMock.

My question is how would I tell the code when to use coolMock or coolObject? I've looked it up online, and a few people have suggested dependency injection, but I'm not sure I understand it correctly.

Thanks in advance!

2

2 Answers 2

1
def doSomething(cool_object=None): cool_object = cool_object or coolObject() ... 

In you test:

def test_do_something(self): cool_mock = mock.create_autospec(coolObject, ...) cool_mock.coolOperation.side_effect = ... doSomthing(cool_object=cool_mock) ... self.assertEqual(cool_mock.coolOperation.call_count, ...) 
Sign up to request clarification or add additional context in comments.

Comments

1

As Dan's answer says, one option is to use dependency injection: have the function accept an optional argument, if it's not passed in use the default class, so that a test can pass in a moc.

Another option is to use the mock library (here or here) to replace your coolObject.

Let's say you have a foo.py that looks like

from somewhere.else import coolObject def doSomething(): x = coolObject() x.coolOperation() 

In your test_foo.py you can do:

import mock def test_thing(): path = 'foo.coolObject' # The fully-qualified path to the module, class, function, whatever you want to mock. with mock.patch('foo.coolObject') as m: doSomething() # Whatever you want to assert here. assert m.called 

The path you use can include properties on objects, e.g. module1.module2.MyClass.my_class_method. A big gotcha is that you need to mock the object in the module being tested, not where it is defined. In the example above, that means using a path of foo.coolObject and not somwhere.else.coolObject.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.