unit-testingmockingpython-2.6unittest2

Mock object issue


I am using mock from voidspace and trying to execute some tests using unittest2 and the behaviour is strange. When i use "@patch.object(Test,'asd')" as a patch i get the mock object in the function arguments. If i use @patch.object(Test,'asd',new_fun) as patch i dont get the one of the parameters. I am using mock-1.0.1

Here you can see a small sample of code that exemplifies the problem. I want to try to understand if this issue is a problem with the way i do the patch or if this is a problem in the library.

import unittest2 as unittest
from mock import patch

class Test:
  def asd(self, a, b =""):
     print "1"


class Test1:
   def kk(self, l):
      Test().asd("1")
   def kk1(self, l):
      Test().asd("1","1")

@patch.object(Test,'asd')
class MockClassUT(unittest.TestCase):
    def test_stat_process(self, my_mock):
        t = Test1()
    def test_stat_process1(self, my_mock):
        t = Test1()
    def test_stat_process2(self, my_mock):
        t = Test1()


def new_fun(*args, **kwargs):
  print "1"


@patch.object(Test,'asd',new_fun)
class MockClassUT1(unittest.TestCase):
    def test_stat_process(self, my_mock):
        t = Test1()
        t.kk("1")
        my_mock.assert_called_with("k")


testloader = unittest.TestLoader()
testnames = testloader.getTestCaseNames(MockClassUT)
suite = unittest.TestSuite()
for name in testnames:
    suite.addTest(MockClassUT(name))

testnames = testloader.getTestCaseNames(MockClassUT1)
for name in testnames:
    suite.addTest(MockClassUT1(name))

print testnames
unittest.TextTestRunner(verbosity=2).run(suite)

Solution

  • This is expected behaviour. You have mocked it as a class decorator and you've also specified the new function new_fun. As such the mocked object won't be passed to each of the methods in the test class.

    This means you can't expect my_mock as parameter there and it also means you can't write assertions using my_mock.

    Furthermore, as an aside, your mocked method new_fun doesn't have the same signature as the method you're mocking (asd). The method asd expects self, a, b="" whereas new_fun doesn't have arguments so I expect an issue to come up there as well when the mocked method is called.