Hussnain Raza
Hussnain Raza

Reputation: 51

Unable to raise Exception while mocking a whole python class in unittest

Here is the original class:

class Original(object):
    def __ init__(self, path):
        self.xml = None
        self.path = path
        self.convert() # <----- I can't modify anything in my class

    def convert(self):
        #some code here
        self.xml = external_api_call # <------------this generates objects for this property
        self.transform()

    def transform(self):
        #some code
        if not self._xml:
            raise Exception('None value')
        for project in self.xml.projects:
            try:
                value = getattr(project, "name")
            except AttributeError:
                raise Exception('AttributeError')
            print('Yes it worked')

I want to have 100% coverage therefore, i tried to generate mock objects for external api calls. Unfortunately while using a mock object it never raises any exception.

with mock.patch('something.Original', autospec=True) as mock_object:
    mock_object.xml = None
    mock_object.transform()

It should generate an exception but it doesn't. I have also tried different approaches e.g side_effect property of mock object.

mock_object._xml.return_value

Upvotes: 0

Views: 264

Answers (1)

Ashutosh gupta
Ashutosh gupta

Reputation: 447

@patch('something.Original')
def test_case_1(Original):
    Original.xml.side_effect = Exception()
    Original.transform()

Upvotes: 1

Related Questions