2016-05-04 74 views
2
class TestHBVbs3(object): 
     @patch.object(Hbvbs3, 'GetConfigClass') 
     def test_get_grower_list(self, config_data, mock_requests_get): 
      # Arrange 
      config_data.return_value = ConfigMock() 
      post_response = {'1st_key': '1st_value', '2nd_key': '2nd_Value'} 
      mock_requests_get.return_value = MagicMock(status_code=200, post_response=post_response) 

      # Act 
      sut = Hbvbs3() 
      the_response = sut.get_growers_list() 

      # Assert 
      assert_equals(the_response.response["1st_key"], mock_requests_get.return_value.response["1st_key"]) 
      assert_equals(the_response.response["2nd_key"], mock_requests_get.return_value.response["2nd_key"]) 
      assert_equals(the_response.response, mock_requests_get.return_value.response) 
      assert_equals(the_response.status_code, mock_requests_get.return_value.status_code) 

Actual code in hbvbs3.py: 
class Hbvbs3(object): 
     _logger = log.logging.getLogger("Hbvbs3") 

    def get_growers_list(self): 
      dbconfig = GetConfigClass() 

我的问题单元测试: 我无法弄清楚如何成功地使用注释嘲笑这样的:@ patch.object(Hbvbs3,“GetConfigClass”)#这片的代码不起作用。 我不得不最终将GetConfigClass实例化放入实用程序方法中,并模拟该调用,但希望能够在方法本身中实际模拟此特定实例化方面获得帮助:“get_growers_list(self):”... - 在我的类Hbvbs3的实例方法中,如何使用模拟注释成功地模拟这种实例化? 我试图在注释中的各种组合,如:这些工作Python的嘲讽使用Py.Test

@patch('Hbvbs3.GetConfigClass') 
@patch.object(Hbvbs3, '__main__.GetConfigClass') 
@patchHbvbs3('_get_growers_list.GetConfigClass') 

无,那么,有没有办法简单地莫克这种使用注释Python中实例化?这看起来并不困难,但如果我能找到注释的正确组合,我就会大伤脑筋。 请让我知道我要去哪里错了? 谢谢!

回答

0

它看起来像你的文件hbvbs3.py代码有这种import语句的顶部:

from config import GetConfigClass 

...和GetConfigClass作为你已经证明里面Hbvbs3。因此,要与Mock实例来替换GetConfigClass,您可以使用patch装饰形式:

@patch('[...].hbvbsp3.GetConfigClass') 

您需要确保所使用的路径是对hbvbsp3模块的完整路径(更换[...] - 我通常使用为了清晰起见,从项目的根目录开始完整的Python路径)。我总是发现Where to patch上的文档很有用。

+0

谢谢。我会试试这个,让你知道它是否有效。我感谢帮助! –