简体   繁体   English

你如何测试特定的 Rust 错误?

[英]How do you test for a specific Rust error?

I can find ways to detect if Rust gives me an error,我可以找到检测 Rust 是否给我错误的方法,

assert!(fs::metadata(path).is_err())

source 来源

How do I test for a specific error?如何测试特定错误?

You can directly compare the returned Err variant if it impl Debug + PartialEq :如果impl Debug + PartialEq您可以直接比较返回的Err变量:

#[derive(Debug, PartialEq)]
enum MyError {
    TooBig,
    TooSmall,
}

pub fn encode(&self, decoded: &'a Bytes) -> Result<&'a Bytes, MyError> {
    if decoded.len() > self.length() as usize {
        Err(MyError::TooBig)
    } else {
        Ok(&decoded)
    }
}
assert_eq!(fixed.encode(&[1]), Err(MyError::TooBig));

Following solution doesn't require PartialEq trait to be implemented.以下解决方案不需要实现PartialEq特征。 For instance std::io::Error does not implement this, and more general solution is required.例如std::io::Error没有实现这一点,需要更通用的解决方案。

In these cases, you can borrow a macro assert_matches from matches crate .在这些情况下,您可以从matches crate 中借用宏assert_matches It works by giving more succinct way to pattern match, the macro is so short you can just type it too:它通过提供更简洁的模式匹配方式来工作,宏很短,你也可以输入它:

macro_rules! assert_err {
    ($expression:expr, $($pattern:tt)+) => {
        match $expression {
            $($pattern)+ => (),
            ref e => panic!("expected `{}` but got `{:?}`", stringify!($($pattern)+), e),
        }
    }
}

// Example usages:
assert_err!(your_func(), Err(Error::UrlParsingFailed(_)));
assert_err!(your_func(), Err(Error::CanonicalizationFailed(_)));
assert_err!(your_func(), Err(Error::FileOpenFailed(er)) if er.kind() == ErrorKind::NotFound);

Full playground buildable example, with example Error enum:完整的操场可构建示例,示例Error枚举:

#[derive(Debug)]
pub enum Error {
    UrlCreationFailed,
    CanonicalizationFailed(std::io::Error),
    FileOpenFailed(std::io::Error),
    UrlParsingFailed(url::ParseError),
}

pub fn your_func() -> Result<(), Error> {
    Ok(())
}

#[cfg(test)]
mod test {
    use std::io::ErrorKind;
    use super::{your_func, Error};

    macro_rules! assert_err {
        ($expression:expr, $($pattern:tt)+) => {
            match $expression {
                $($pattern)+ => (),
                ref e => panic!("expected `{}` but got `{:?}`", stringify!($($pattern)+), e),
            }
        }
    }

    #[test]
    fn test_failures() {
        // Few examples are here:
        assert_err!(your_func(), Err(Error::UrlParsingFailed(_)));
        assert_err!(your_func(), Err(Error::CanonicalizationFailed(_)));
        assert_err!(your_func(), Err(Error::FileOpenFailed(er)) if er.kind() == ErrorKind::NotFound);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM