简体   繁体   English

python side_effect - 方法的模拟行为

[英]python side_effect - mocking behavior of a method

In the mock, I want a certain function to return a new value in the test. 在mock中,我希望某个函数在测试中返回一个新值。 This is how i did it. 这就是我做到的。

Class MyClass:

      my_var = None  

      def foo(self, var1):
          return somevalue

      def bar(self):
          my_var = foo(1)

Class TestClass(unittest.TestCase):
      myClass = MyClass() 

      def _side_effect_foo(var1):
           if condition:
                return new_value

      @patch("MyClass", "foo", side_effect='_side_effect_foo')
      def test_foo(self):
           self.myClass.bar()

This gives me a error: 这给了我一个错误:

Can't pass kwargs to a mock we aren't creating. 无法将kwargs传递给我们没有创建的模拟。

Am I using the correct format of side_effect? 我使用正确的side_effect格式吗?

Thanks for any help! 谢谢你的帮助!

There are a few issues here. 这里有一些问题。

  1. The arguments you're passing to the @patch decorator aren't quite right. 你传递给@patch装饰器的参数不太正确。 The target should be specified as a single argument: 应将目标指定为单个参数:

     @patch('MyClass.foo') 
  2. Your decorated test function will need to accept an additional argument for the patched target - eg mock_foo : 你的修饰测试函数需要接受修补目标的附加参数 - 例如mock_foo

     @patch('MyClass.foo') def test_foo(self, mock_foo): 
  3. You can then set the side effect on mock_foo : 然后,您可以在mock_foo上设置mock_foo

     @patch('MyClass.foo') def test_foo(self, mock_foo): mock_foo.side_effect = self._side_effect_foo 
  4. In addition, _side_effect_foo() should be made a proper instance method with self as the first argument: 另外, _side_effect_foo()应该成为一个正确的实例方法,并将self作为第一个参数:

     def _side_effect_foo(self, var1): if condition: return new_value 
  5. Lastly, you should instantiate MyClass either inside the test method itself, or inside the setUp() method: 最后,您应该在测试方法本身内部或在setUp()方法内实例化MyClass

     def setUp(self): self.myClass = MyClass() @patch('MyClass.foo') def test_foo(self, mock_foo): mock_foo.side_effect = self._side_effect_foo self.myClass.bar() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM