2017年8月25日 星期五

[ Python 常見問題 ] Using mock patch to mock an instance method

Source From Here 
Question 
I'm trying to mock something while testing a Django app using the imaginatively named Mock testing library. I can't seem to quite get it to work, I'm trying to do this: 
- models.py 
  1. #!/usr/bin/env python3  
  2. class Promotion(object):  
  3.     def __init__(self):  
  4.         pass  
  5.   
  6.     def bar(self):  
  7.         return "Do something I don't want!"  
How do I mock the method bar of the creating object of class Promotion

How-To 
Check below sample code: 
- test.py 
  1. import models  
  2. from unittest import TestCase  
  3. from unittest.mock import patch  
  4.   
  5. class ViewsDoSomething(TestCase):  
  6.     def setUp(self):  
  7.         self.mockMsg = 'Do what I want'  
  8.   
  9.   
  10.     @patch.object(models.Promotion, 'bar')  
  11.     def test_enter_promotion(self, mockObj):  
  12.         mockObj.return_value = self.mockMsg  
  13.   
  14.         p = models.Promotion()  
  15.         self.assertTrue(p.bar() == self.mockMsg)  
Then you can test it this way: 
# pytest -v test.py
...
test.py::ViewsDoSomething::test_enter_promotion PASSED
...


Supplement 
Python 文章收集 - 用 Mock 來做 Python Unit Test 
Python 文章收集 - pytest introduction

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...