首页 > 解决方案 > 如何测试特定类型的盒装错误?

问题描述

我在我的库中创建了以下错误:

#[derive(Debug, PartialEq)]
pub enum BridgeError {
  TLVLength { expected: usize, received: usize },
}

impl Error for BridgeError {
  fn description(&self) -> &str {
    match self {
      BridgeError::TLVLength { expected, received } => "",
    }
  }
}

impl fmt::Display for BridgeError {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match self {
      BridgeError::TLVLength { expected, received } => {
        write!(f, "Header declared {} bytes, received {} bytes.", expected, received)
      }
    }
  }
}

我有一个返回结果的方法:

pub(crate) fn from_byte_array(barray: &[u8]) -> Result<TypeLengthValue, Box<dyn std::error::Error>> {
...
return Err(
        BridgeError::TLVLength {
          received: length,
          expected: barray.len(),
        }
        .into();
...
}

我想实现一个导致方法失败的测试,这样我就可以确保返回正确的错误类型:

#[test]
  fn test_from_byte_array_with_wrong_length() {
    let bytes = &[75, 0, 0, 0, 14, 0, 0, 149, 241, 17, 173, 241, 137];
    let tlv = TypeLengthValue::from_byte_array(bytes).unwrap_err();
    let err = tlv.downcast::<BridgeError>().unwrap();

    //assert_eq!(err, BridgeError::TLVLength{expected: 12, received: 14});
  }

我不知道如何从Box<dyn std::error::Error>.

标签: rust

解决方案


Box在执行以下操作之前取消引用assert_eq

let err = tlv.downcast::<BridgeError>().unwrap();
assert_eq!(*err, BridgeError::TLVLength{expected: 12, received: 14});

(操场)


推荐阅读