robotframework测试用例创建自定义库类的新实例时传递参数

时间:2018-07-13 03:02:26

标签: robotframework

有一个用Python编写的自定义RF库:

class ALibrary:
    def __init__(self, name):
        self._name = name
    def get_name(self):
        print "*WARN*" + self._name

在设置中导入该库

*** Settings ***
Library          lib/ALibrary.py LaoWang
  

默认情况下,它将为每个测试用例创建新的测试库实例。

我的理解是,__init__(self, name)在每个测试用例的开头都会被调用,例如:

*** Test Cases ***
Test Case 1
    get name
Test Case 2
    get name

机器人框架应该为Test Case 1创建一个实例,为Test Case 2创建另一个实例,但是,我的__init__(self, name)需要一个参数,如何在*** Test Cases ***中传递该参数?

进行了测试:

$ python -m robot test.1.robot
==============================================================================
Test.1
==============================================================================
[ WARN ] LaoWang
Case 1                                                                | PASS |
------------------------------------------------------------------------------
[ WARN ] LaoWang
Case 2                                                                | PASS |
------------------------------------------------------------------------------
Test.1                                                                | PASS |
2 critical tests, 2 passed, 0 failed
2 tests total, 2 passed, 0 failed

两个案例都显示了老王,这是否意味着RF并没有在不同的测试案例中创建新实例?

1 个答案:

答案 0 :(得分:1)

由于这个问题与测试库范围有关,因此我确实想链接到该主题的Robot Framework documentation。应该读取的方式是,对于每个测试用例,都以相同的方式重新初始化设置中的库。下面是一个说明这种行为的示例:

ALibrary.py

class ALibrary:

    ROBOT_LIBRARY_SCOPE = 'TEST CASE'

    def __init__(self, name):
        self._name = name

    def get_name(self):
        print "*WARN*" + self._name

    def set_name(self, name):
        self._name = name     

ALibrary.robot

*** Settings ***
Library          ALibrary   LaoWang

*** Test Cases ***
Test Case 1
    get name
    set name    New Name
    get name

Test Case 2
    get name
    set name    Another New Name
    get name

在以下结果中,您可以看到,即使在第一个测试用例中设置了新名称之后,设置初始化中的默认名称也会在第二个测试用例中返回。

==============================================================================
TestProject                                                                   
==============================================================================
TestProject.ALibrary                                                          
==============================================================================
Test Case 1                                                           
[ WARN ] LaoWang
[ WARN ] New Name
| PASS |
------------------------------------------------------------------------------
Test Case 2                                                           
[ WARN ] LaoWang
[ WARN ] Another New Name
| PASS |
------------------------------------------------------------------------------
TestProject.ALibrary                                                  | PASS |
2 critical tests, 2 passed, 0 failed
2 tests total, 2 passed, 0 failed
==============================================================================