中的临时“取消匹配”功能模拟侧边_

2024-10-01 11:35:52 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法在side_effect内使用mock临时撤消修补? 特别是我想做一些类似的事情:

from mock import patch
import urllib2
import unittest

class SimpleTest(unittest.TestCase):
    def setUp(self):
        self.urlpatcher = patch('urllib2.urlopen')
        self.urlopen = self.urlpatcher.start()

        def side_effect(url):
            #do some interesting stuff first

            #... temporary unpatch urllib2.urlopen so that we can call a real one here
            r = urllib2.urlopen(url) #this ought to be the real deal now
            #... patch it again

            return r

        self.urlopen.side_effect = side_effect

    def test_feature(self):
        #almost real urllib2.urlopen usage goes here
        p = urllib2.urlopen("www.google.com").read()


if __name__ == '__main__':
    unittest.main()

Tags: importselfurlheremaindefunittesturllib2
3条回答

我不确定这一点,但我认为只有在你做了setContentView()之后,你才能做getTabHost()。否则,getTabHost()返回null(此行为类似于findViewById()

堆栈跟踪指向此行作为异常源:

Resources res = getResources(); 

继承的getResources()方法正在引发异常。这是因为在构建和初始化活动之前,您不能调用getResources()。将这些成员变量初始化移到onCreate()中,您就可以开始了

需要在onCreate中定义以下行

Resources res = getResources(); 
TabHost tabHost = getTabHost(); 

相关问题 更多 >