如何使用pymox对此代码进行单元测试?

如何使用pymox对此代码进行单元测试?

问题描述:

所以我已经安装了pymox,我想测试这个方法:如何使用pymox对此代码进行单元测试?

class HttpStorage(): 

    def download(self, input, output): 
     try: 
      file_to_download = urllib2.urlopen(input) 
     except URLError: 
      raise IOError("Opening input URL failed") 

     f = open(output, "wb") 
     f.write(file_to_download.read()) 
     f.close() 
     return True 

我通过pymox文档阅读,但我无法弄清楚如何做到这一点。你能帮我一些示例代码吗?

+0

偏题,但为什么要使用'pymox'呢? stdlib'unittest'模块似乎非常充实。 – 2014-09-19 21:26:18

import unittest 
import mox 

class HttpStorageTest(mox.MoxTestBase): 

    def setUp(self): 
    self.httpstorage = HttpStorage() 

    def test_download(self): 
    self.mox.StubOutWithMock(urllib2, "urlopen") 
    test_file = open("testfile") 
    urllib2.urlopen(mox.IgnoreArg()).AndReturn(test_file) 

    self.mox.ReplayAll() 
    feedback = self.httpstorage.download(test_input, test_output) 
    self.assertEqual(feedback, True) 

你可以试试这个格式来测试你的下载功能可按作为urllib2.openurl()已被嘲笑做单元测试。