简体   繁体   中英

Python unittest test passed in class method is called with

I have a method that takes two inputs a emailer class and a dict of data.

def send_email(data, email_client):
     **** various data checks and formatting *****
     response_code = email_client.create_email(recipient=receipient
                                               sender=sender
                                               etc...)

I am trying to write a unit test that will assert email_client.create_email was called with the correct values based on the input data.

In my test file I have

from emailer.email import send_email

class TestEmails(unittest.TestCase):

    def test_send_email(self):
        email.send_email(get_transactional_email_data, MagicMock())

I normally test what a method is called with by something similar to:

mock.assert_called_with(recipient=receipient
                       sender=sender
                       etc..)

However, since this time I'm testing what a passed in class is being called with (and a MagicMock) I don't know how it should be done.

I don't think you need MagicMock. Just create the mocks upfront

from emailer.email import send_email

class TestEmails(unittest.TestCase):

def test_send_email(self):
    myclient = Mock()
    mycreate = Mock()
    myclient.create_email = mycreate
    email.send_email(get_transactional_email_data, myclient)
    self.assertTrue(
        mycreate.called_with(sender='...')
    )

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