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});