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, 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>
.
解决方案
Box
在执行以下操作之前取消引用assert_eq
:
let err = tlv.downcast::<BridgeError>().unwrap();
assert_eq!(*err, BridgeError::TLVLength{expected: 12, received: 14});
推荐阅读
- python - Python从数组中绘制平行于y轴的线
- azure - 相同服务的 Kubernetes 多个 POD 实例的日志配置
- linux - 如何在 Linux / macOS 上将 Sass 与 NetBeans 一起使用
- python-3.x - 拆开熊猫数据框
- java - Spring Boot:打开数据库连接时设置 PostgreSQL 运行时参数
- javascript - Electron 应用程序运行没有任何错误,但窗口没有打开或在任务管理器中显示
- java - 如何将字符串值拆分为多个值
- scala - Spark Scala S3 存储:权限被拒绝
- sql - 如何在 SQL 查询(Oracle)中使用当前时间戳
- angular - 使用 Angular 4 取消 http 请求