Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

11.5 在测试中使用Result<T, E>

11.5.1. 测试函数返回Result枚举

到目前为止,测试失败的原因一直都是panic!,但这并不是测试失败的唯一方式。

使用Result枚举的测试也比较好写。只需要接收被测试代码的返回值:如果符合预期,就返回Ok变体;否则返回Err变体。又因为枚举变体可以附带数据,还可以在Err上附带错误信息,帮助调试。

如果是Ok,测试就通过;否则就失败。

看个例子:

#![allow(unused)]
fn main() {
pub fn add(left: usize, right: usize) -> usize {
    left + right
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() -> Result<(), String> {
        let result = add(2, 2);

        if result == 4 {
            Ok(())
        } else {
            Err(String::from("two plus two does not equal four"))
        }
    }
}
}

it_works函数的返回类型是Result<(), String>。测试通过时返回Ok(());测试失败时返回包含错误信息StringErr

这个测试肯定能通过。

让测试返回Result<T, E>,还可以在测试函数体里使用?运算符:任何一步返回Err时,测试就会失败,写起来很方便。

使用Result进行测试时有一点要注意:不要在用Result<T, E>编写的测试上使用should_panic属性(11.4. 用should_panic检查恐慌 中讲过)。若要断言某个操作返回Err,应使用类似assert!(value.is_err())的写法,而不是?