Cucumber 版本
确保使用与您用于 cucumber-java
或 cucumber-java8
相同的 cucumber-junit
版本。
您的 Then
步骤应进行断言,比较预期结果和应用程序的实际结果。
Cucumber 没有自带断言库。请使用单元测试工具中的断言方法。
使用 cucumber-junit-platform-engine 时,您可以自由使用任何您选择的断言库。例如
当使用 JUnit 4 运行 Cucumber 时,我们建议使用 JUnit 4 的 assert*
方法。
如果您使用的是 Maven,请将以下内容添加到您的 pom.xml
中
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>5.11.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>7.20.1</version>
<scope>test</scope>
</dependency>
以下是一个使用 assertEquals
的示例
import static org.junit.Assert.*;
public class Example {
@Then("the result should be {int}")
public void the_result_should_be(int expectedResult) {
assertEquals(expectedResult, result);
}
}
有关如何使用 JUnit 断言的更多示例,请参阅 JUnit Wiki。
您也可以使用 TestNG 的断言。
如果您使用的是 Maven,请将以下内容添加到您的 pom.xml
中
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.10.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>7.20.1</version>
<scope>test</scope>
</dependency>
TestNG 断言类似于 JUnit。有关如何将 TestNG 与 Cucumber 结合使用的更详细示例,请参阅 calculator-java-testng 示例。
有关如何使用 TestNG 断言的更多信息,请参阅 TestNG 文档。
我们建议使用 Node.js 内置的 assert 模块。
const assert = require('assert')
Then('the result should be {word}', function (expected) {
// this.actual is typically set in a previous step
assert.equal(this.actual, expected)
})
如果您愿意,可以使用任何其他断言库。以下是一个使用 Chai 的示例
const { expect } = require('chai')
Then('the result should be {word}', function (expected) {
expect(this.actual).to.eql(expected)
})
我们建议使用 RSpec 进行断言。
将 rspec-expectations
gem 添加到您的 Gemfile
中。Cucumber 会自动加载 RSpec 的匹配器和期望方法,使其在您的步骤定义中可用。例如
Given /^a nice new bike$/ do
expect(bike).to be_shiny
end
如果您想配置 RSpec,您还需要将 rspec-core
gem 添加到您的 Gemfile
中。然后,您可以将以下内容添加到您的 features/support/env.rb
配置中,例如
RSpec.configure do |config|
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
请注意,测试/断言/期望要么“通过”,要么“失败”(引发错误),并且“失败”与 false
不同。除了“失败”之外的所有内容都算作通过。
在 RSpec 中,当 something.should_be 0
并且实际并非如此时,返回的是一个错误异常,而不是一个布尔值。在 Cucumber 中,人们会写 fail if false
,而不仅仅是 false
。这是因为 false
可能是测试的预期成功结果,因此不是错误。
但是,有时我们希望测试我们的应用程序如何处理异常,因此不希望 Cucumber 处理该异常。在这种情况下,请使用 @allow-rescue
标签。
如果您更喜欢使用 Test::Unit
的 assert
方法,您可以将它们混合到您的 World
中。
require 'test/unit/assertions'
World(Test::Unit::Assertions)
您可以帮助我们改进此文档。 编辑此页面。