【问题标题】:Using python unittest with monkeyrunner vs without monkeyrunner使用带有monkeyrunner的python单元测试与不使用monkeyrunner
【发布时间】:2017-02-25 01:39:50
【问题描述】:

我有这个:

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来自哪里?

【问题讨论】:

    标签: android python python-2.7 unit-testing monkeyrunner


    【解决方案1】:

    您可能已经发现,这是因为monkeyrunner 没有运行setUpClass 方法。

    您可以使用AndroidViewClient/culebra 作为monkeyrunner 的直接替代品,其优势在于它与python 2.x 一起运行,因此您的测试将被正确初始化。

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

    这是来自生成的测试的 sn-p(为了清楚起见,删除了一些行):

    #! /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 和可用设备连接起来,处理命令行选项等。

    【讨论】:

    • 但是为什么monkeyrunner没有调用setUpClass()方法呢?
    • 可能忽略了装饰器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 2020-11-03
    • 2016-05-21
    • 2012-10-15
    相关资源
    最近更新 更多