I have this sort of setup where I'm testing a class which is using another class, and I want to mock the latter so I'm only testing the first class itself.
nuclear_reactor.py:
class NuclearReactor(): def __init__(self): print "initializing the nuclear reactor" def start(self): print "starting the nuclear reactor" nuclear_manager.py:
from nuclear_reactor import NuclearReactor class NuclearManager(): def __init__(self): print "manager creating the nuclear reactor" self.reactor = NuclearReactor() def start(self): print "manager starting the nuclear reactor" self.reactor.start() test_nuclear_manager.py:
from mock import Mock import nuclear_manager from nuclear_manager import NuclearManager def test(): mock_reactor = nuclear_manager.NuclearReactor = Mock() nuke = NuclearManager() nuke.start() nuke.start() print mock_reactor.mock_calls print mock_reactor.start.call_count test() What I'd like to test is that NuclearReactor.start is called, but when I run this I get:
manager creating the nuclear reactor manager starting the nuclear reactor manager starting the nuclear reactor [call(), call().start(), call().start()] 0 Which I totally understand since start is an attribute of the instance and not of the class, and I could parse the mock_calls, but isn't there a better way to check that the call of an instantiated mocked class is made?
I could use dependency injection in NuclearManager to pass a mock NuclearReactor, but I'm thinking there would be an alternative way using just mock.
.start()to be called once when you call the manager twice?NuclearManagerbecause your code now makes the manager set itsreactorinstance to a default value. Only the highest level parts of a program should have defaults.