Mocking a class method that is used via an instance

后端 未结 3 1934
清酒与你
清酒与你 2021-02-03 10:25

I\'m trying to patch a class method using mock as described in the documentation. The Mock object itself works fine, but its methods don\'t: For example, their attributes like <

相关标签:
3条回答
  • 2021-02-03 11:08

    I have found my error: In order to configure the methods of my mock's instances, I have to use mock().method instead of mock.method.

    class Lib:
        """In my actual program, a module that I import"""
        def method(self):
            return "real"
    
    class User:
        """The class I want to test"""
        def run(self):
            l = Lib()
            return l.method()
    
    with patch("__main__.Lib") as mock:
        #mock.return_value = "bla" # This works
        mock().method.return_value = "mock"
        u = User()
        print(u.run())
    
    0 讨论(0)
  • 2021-02-03 11:10
    from mock import *
    
    class Lib:
        """In my actual program, a module that I import"""
        def method(self):
            return "real"
    
    class User:
        """The class I want to test"""
        def run(self, m):
    
            return m.method()
    
    with patch("__main__.Lib") as mock:
        #mock.return_value = "bla" # This works
        mock.method.return_value = "mock"
    
        print User().run(mock)
    
    0 讨论(0)
  • 2021-02-03 11:15

    I mock classmethods like this:

    def raiser(*args, **kwargs):
        raise forms.ValidationError('foo')
    with mock.patch.object(mylib.Commands, 'my_class_method', classmethod(raiser)):
        response=self.admin_client.get(url, data=dict(term='+1000'))
    
    0 讨论(0)
提交回复
热议问题