質問

I'm trying to use patch to return the a Mock from within a method. The basic structure is as follows:

MyCode.py

class MyClass:

    def __init__(self, first_name, last_name):
        self.first = first_name
        self.last = last_name

    def get_greeting(self):
        return 'Hello {f} {l}'.format(f=self.first, l=self.last)


def get_new_greeting(first_name, last_name):
    obj = MyClass(first_name, last_name)
    return obj.get_greeting()


my_code_test.py

import unittest
from mock import Mock, patch
import my_code

class TestMyCode(unittest.TestCase):
    def setUp(self):
        pass

    @patch('my_code.MyClass')
    def test_get_greeting(self, MockClass):
        instance = MockClass.return_value
        mock_greeting = 'Hello Me'
        instance.get_greeting.return_value = mock_greeting

        greeting = my_code.get_new_greeting('john', 'doe')
        self.assertEqual(greeting, mock_greeting)


if __name__ == '__main__':
    unittest.main()

The code above works fine for me. However, when I apply the same pattern to the real code that I'm trying to test, the real object (not the mock one) gets returned in the method being tested. I can't see any differences. The only think that is a bit different is that the real class is defined in a init.py file. I'm not sure if this make a difference or not? Has any seen this before?

Note: the actual lib is twilio 3.3.5 and I'm using Python 2.6.5 and Django 1.3.1 and Mock 0.7.2

正しい解決策はありません

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top