title: Mocking imported class in Python
body: <p>I am trying to mock a class which is called in a module which imports said class, which I want to test.</p>
  
  <pre><code># application.py
  from my_module.my_submodule import MyClass
  
  def my_function(var1):
      instance = MyClass()
  
      instance.some_function(var1)
  </code></pre>
  
  <p>and my testing file</p>
  
  <pre><code># test_application.py
  import mock
  import application
  
  def test_my_function():
      with mock.patch('my_module.my_submodule.MyClass') as MockClass:
          application.my_function(var1)
  
          MockClass.assert_called()        
  </code></pre>
  
  <p>This gives an error saying <code>MockClass</code> was not called.</p>
  
  <p>Now, by looking at this question: <a href="https://stackoverflow.com/questions/20242862/why-python-mock-patch-doesnt-work">Why python mock patch doesn&#39;t work?</a>, I was inspired to change the <code>application.py</code> import to this</p>
  
  <pre><code># application.py
  import my_module.my_submodule as mysub
  
  def my_function(var1):
      instance = mysub.MyClass()
  
      instance.some_function(var1)
  </code></pre>
  
  <p>that is, I don't directly import the class that I want to mock in the test. Now it works. </p>
  
  <p>My question is, if this is working as intended, or I am doing something wrong in the original way? Is it really necessary to always import modules like this, if I want to mock a class used in a module I want to test?</p>