核心原则
在Cucumber测试中,Then步骤必须包含断言,用于比较应用程序返回的实际结果与预期结果是否一致。
Cucumber本身不提供断言功能,需要借助各语言的测试工具中的断言方法。
Java 语言
JUnit 5
使用 cucumber-junit-platform-engine 时,可自由选择任何断言库:
-
AssertJ
-
Hamcrest
-
JUnit Jupiter(自带断言)
JUnit 4
推荐使用 JUnit 4 自带的 assert* 方法。
Maven依赖配置:
XML
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version> <!-- 注意版本修正 -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>7.33.0</version>
<scope>test</scope>
</dependency>
版本一致性提醒: 确保 cucumber-junit 与 cucumber-java 或 cucumber-java8 使用相同版本。
示例代码:
java
import static org.junit.Assert.*;
public class Example {
@Then("结果应为 {int}")
public void the_result_should_be(int expectedResult) {
assertEquals(expectedResult, actualResult); // 比较预期与实际值
}
}
TestNG
TestNG的断言用法与JUnit类似。
Maven依赖配置:
XML
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.11.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>7.33.0</version>
<scope>test</scope>
</dependency>
JavaScript 语言
推荐方案:Node.js 内置 assert 模块
javascript
const assert = require('assert')
Then('结果应为 {word}', function(expected) {
// this.actual 通常在前序步骤中设置
assert.equal(this.actual, expected)
})
也可使用其他断言库(如Chai)
javascript
const { expect } = require('chai')
Then('结果应为 {word}', function(expected) {
expect(this.actual).to.eql(expected)
})
Ruby 语言
推荐方案:RSpec
在 Gemfile 中添加 rspec-expectations gem,Cucumber会自动加载RSpec的匹配器和期望方法。
示例:
ruby
Given /^一辆崭新的自行车$/ do
expect(bike).to be_shiny # 使用RSpec风格的期望表达式
end
如需配置RSpec,还需添加 rspec-core gem,然后在 features/support/env.rb 中配置:
ruby
RSpec.configure do |config|
config.expect_with :rspec do |c|
c.syntax = :expect # 推荐使用 :expect 语法
end
end
备选方案:Test::Unit
如果习惯使用Test::Unit的断言方法,可将其混入World:
ruby
require 'test/unit/assertions'
World(Test::Unit::Assertions)
重要概念:理解"测试失败"
断言失败 vs 布尔值false
在测试中,断言/期望的结果只有两种:
-
通过(不抛出异常)
-
失败(抛出错误异常)
"失败"不等于返回false值,因为false可能是某个测试预期的成功结果。
关键区别
-
断言失败:抛出异常,测试停止,标记为失败
-
布尔值false:只是普通返回值,不影响测试流程