2017-02-25 49 views
0

我有这样的:使用Python单元测试与monkeyrunner VS不monkeyrunner

import unittest 
import sys, os 
sys.path.append(os.path.dirname(sys.argv[0])) 

class TestStringMethods(unittest.TestCase): 

     @classmethod  
     def setUpClass(cls): 
      cls.g = "def" 
      print cls 

     def test_upper(self): 
      self.assertEqual('DeF'.lower(), TestStringMethods.g) 
if __name__ == '__main__': 
    unittest.main() 

python test.py

给出:

python screen_test.py 
<class '__main__.TestStringMethods'> 
. 
---------------------------------------------------------------------- 
Ran 1 test in 0.001s 

OK 

但是,这样的:

monkeyrunner "%CD%\test.py" 

给出:

E 
====================================================================== 
ERROR: test_upper (__main__.TestStringMethods) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "C:\Users\abc\def\ghi\jkl\test.py", line 29, in test_upper 
    self.assertEqual('DeF'.lower(), TestStringMethods.g) 
AttributeError: type object 'TestStringMethods' has no attribute 'g' 

---------------------------------------------------------------------- 
Ran 1 test in 0.024s 

FAILED (errors=1) 

为什么同样的测试时monkeyrunner运行失败?

另外哪里来的是唯一的E来自哪里?

回答

1

正如您可能已经发现的那样,这是因为monkeyrunner未运行setUpClass方法。

您可以使用AndroidViewClient/culebra作为monkeyrunner的插入替代品,其优点是可以使用python 2.x运行,因此您的测试将被正确初始化。

此外,culebra -U可以自动生成测试,然后您可以自定义测试。

这是从生成的测试的一个片段(为了清楚起见移除了一些行):

#! /usr/bin/env python 
# ...  
import unittest 

from com.dtmilano.android.viewclient import ViewClient, CulebraTestCase 

TAG = 'CULEBRA' 


class CulebraTests(CulebraTestCase): 

    @classmethod 
    def setUpClass(cls): 
     # ... 
     cls.sleep = 5 

    def setUp(self): 
     super(CulebraTests, self).setUp() 

    def tearDown(self): 
     super(CulebraTests, self).tearDown() 

    def preconditions(self): 
     if not super(CulebraTests, self).preconditions(): 
      return False 
     return True 

    def testSomething(self): 
     if not self.preconditions(): 
      self.fail('Preconditions failed') 

     _s = CulebraTests.sleep 
     _v = CulebraTests.verbose 

     ## your test code here ## 



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

CulebraTestCase提供繁重,连接测试用adb和可用的设备,处理所述命令行选项,等等。

+0

但为什么monkeyrunner不能调用setUpClass()方法? – abc

+0

也许是忽略了装饰者 –