user1452759
user1452759

Reputation: 9470

Python mock: How to mock a class being called from the class method being tested

Let's say I have the below code:

bm.py    

from a.b import AC
class B:
    def __init__(self, **kwargs):
         self.blah = kwargs["blah"]
    def foo(self, message):
         # Do something here and then finally use AC().send()
         AC().send(message)

I am writing the below test case for the above:

import pytest
import unittest
from mock import patch
from a.b import AC
import B

class TestB(unittest.TestCase):
    @patch('AC.send')
    def test_foo(self, mock_send):
         s = B(blah="base")
         s.foo("Hi!")
         ## What to assert here???

I would like to mock the AC.send. AC.send doesn't return anything because it is "sending" to some external service/machine. And also, B.foo() doesn't return anything either. So I'm not sure what I should assert and check?

With the above test case I get the below error:

ModuleNotFoundError: No module named 'AC'

I'm new to Unit test cases and mocking.

Upvotes: 0

Views: 76

Answers (3)

Lior Cohen
Lior Cohen

Reputation: 5755

regarding

ModuleNotFoundError: No module named 'AC'

You should use the full quilifired name in @patch - in your case @patch('a.b.AC.send')

regarding

## What to assert here??? 

This question is too broad and application dependent. Generally, you need to ask yourself what is expected from the production code. Sometimes you only want to check that there are no exceptions. In this case you don't need to assert anything. If there will be an exception, the test will fail.

Suggest to read this fine post this

Upvotes: 1

user1452759
user1452759

Reputation: 9470

Based on what @Florian Bernard mentioned in the comment section, the below works!

import pytest
import unittest
from mock import patch
from a.b import AC
import B

class TestB(unittest.TestCase):
     @patch('a.b.AC.send') ##Provide the full import
     def test_foo(self, mock_send):
         s = B(blah="base")
         s.foo("Hi!")

Upvotes: 0

Florian Bernard
Florian Bernard

Reputation: 2569

You can use the full import.

@patch('a.b.AC.send')

Upvotes: 0

Related Questions