Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 如何测试特定类型的装箱错误?_Rust - Fatal编程技术网

Rust 如何测试特定类型的装箱错误?

Rust 如何测试特定类型的装箱错误?,rust,Rust,我在我的库中创建了以下错误: #[derive(Debug, PartialEq)] pub enum BridgeError { TLVLength { expected: usize, received: usize }, } impl Error for BridgeError { fn description(&self) -> &str { match self { BridgeError::TLVLength { expected,

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

#[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();
...
}
pub(板条箱)fn来自字节数组(barray:&[u8])->结果{
...
返回错误(
BridgeError::TLVLength{
收到:长度,
应为: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});
  }
#[测试]
fn从字节数组测试长度错误的字节{
让字节=&[75,0,0,0,14,0,0,149,241,17173241,137];
让tlv=TypeLengthValue::from_byte_数组(字节)。unwrap_err();
让err=tlv.downcast::().unwrap();
//assert_eq!(err,BridgeError::TLVLength{expected:12,received:14});
}

我搞不清楚的是,在执行
断言之前,如何从
框中获取正确的错误类型
取消对
框的引用

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

在执行
assert\u eq
之前,请取消对
框的引用:

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