ruipacheco
ruipacheco

Reputation: 16422

How can I test my Boxed error for a specific type?

I created the following error in my library:

#[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)
      }
    }
  }
}

I have a method that returns a Result:

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

I'd like to implement a test that causes the method to fail so I can make sure the right error type is being returned:

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

What I can't figure out is how to get the right error type out of the Box<dyn std::error::Error>.

Upvotes: 0

Views: 130

Answers (1)

loops
loops

Reputation: 5635

Dereference the Box before doing the assert_eq:

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

(playground)

Upvotes: 2

Related Questions