2017-02-25 78 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

也許是忽略了裝飾者 –