简体   繁体   中英

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.

regarding

ModuleNotFoundError: No module named 'AC'

You should use the full quilifired name in @patch - in your case @patch('abAC.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

You can use the full import.

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

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!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM