测试过程中,同一个测试场景经常需要使用不同的测试数据来覆盖验证。在Behave中,我们可以通过Scenario Outlines来实现这种数据驱动的功能。
1 Scenario Outline: search keyword from Baidu 2 Given The index page of Baidu is ready 3 When I input <keyword> in a search text field, and click search button 4 Then The <keyword> should appear in page title 5 6 Examples: 7 | keyword | 8 | python | 9 | selenium | 10 | behave |
上面例子中,我们在When语句中指定了参数,并且在Examples中写出了变量的参数值。Behave在运行测试用例时,会将Examples中定义的参数值传入,每个参数值代表一个测试用例。
step实现代码如下:
1 @given('The index page of Baidu is ready') 2 def step_impl(context): 3 context.driver.get("https://www.baidu.com") 4 assert context.driver.find_element_by_id('kw') is not None 5 6 @when('I input {keyword} in a search text field, and click search button') 7 def step_impl(context, keyword): 8 context.driver.find_element_by_id('kw').send_keys(keyword) 9 context.driver.find_element_by_id('su').click() 10 sleep(2) 11 12 @then('The {keyword} should appear in page title') 13 def step_impl(context, keyword): 14 assert keyword in context.driver.title
执行结果如下:
1 When I input python in a search text field, and click search button # features/steps/tutorial.py:21 2 Then The python should appear in page title # features/steps/tutorial.py:27 3 4 @slow 5 Scenario Outline: search keyword from Baidu -- @1.2 # features/tutorial.feature:17 6 Given The index page of Baidu is ready # features/steps/tutorial.py:16 7 When I input selenium in a search text field, and click search button # features/steps/tutorial.py:21 8 Then The selenium should appear in page title # features/steps/tutorial.py:27 9 10 @slow 11 Scenario Outline: search keyword from Baidu -- @1.3 # features/tutorial.feature:18 12 Given The index page of Baidu is ready # features/steps/tutorial.py:16 13 When I input behave in a search text field, and click search button # features/steps/tutorial.py:21 14 Then The behave should appear in page title # features/steps/tutorial.py:27 15 16 1 feature passed, 0 failed, 0 skipped 17 3 scenarios passed, 0 failed, 1 skipped 18 9 steps passed, 0 failed, 3 skipped, 0 undefined 19 Took 0m29.792s
更多资料可参考官方文档:https://behave.readthedocs.io/en/stable/tutorial.html#features