-
框架介绍
为了复用原有 Android 端和 iOS 端的 feature 用例,rust 下也选择 cucumber 框架做为单元测试框架。这一选择允许我们无缝地将已有的测试用例迁移至Rust环境中执行。
Cucumber是一种行为驱动开发(BDD)的工具,允许开发人员利用自然语言描述功能测试用例。这些测试用例按特性(Features)组织,并通过一系列场景(Scenarios)详述,每个场景由数个操作步骤(Steps)构成。
rust 下的 cucumber 框架为cucumber,该库为异步测试提供了良好支持。
为了实现接口的模拟测试,推荐使用mockall库,它是Rust中的一个模拟框架,类似于Android的Mockito 以及PowerMock,和iOS的OCMock,支持广泛的模拟功能。
结合Cucumber和mockall,我们能够高效地编写Rust库的单元测试。
-
Rust Cucumber 介绍
-
配置 Cucumber
首先,在Cargo.toml
文件的[dev-dependencies]
部分加入以下依赖:
ini
复制代码
[dev-dependencies] cucumber = "0.21.0" tokio = { version = "1.38.0", features = ["macros", "rt-multi-thread", "time"] } [[test]] name = "example" # this should be the same as the filename of your test target harness = false # allows Cucumber to print output instead of libtest
Cucumber框架在Rust中是异步实现的,因此需引入tokio
框架以支持异步执行Cucumber的run
方法。
测试文件需要放于项目的tests
目录下。创建tests/example.rs
文件,并在里面定义测试的入口点。
-
Rust Cucumber 实例解析
我们在 example.rs中,写一个完整的单元测试实例:
rust
复制代码
#[derive(Debug, Default)] pub struct AirCondition { pub temperature: i8, } impl AirCondition { pub fn new(temperature: i8) -> Self { AirCondition { temperature } } pub fn adjust_temperature(&mut self, value: i8) { self.temperature += value; } pub fn current_temperature(&self) -> i8 { self.tempe