代码之家  ›  专栏  ›  技术社区  ›  goofballLogic

Rust panic单元测试比较字符串消息

  •  0
  • goofballLogic  · 技术社区  · 6 年前

    我在寻找一种方法来断言一段代码会死机,并且死机消息包含一个特定的字符串。我想出了以下似乎有效的方法:

    let actual = std::panic::catch_unwind(|| decode(notation.to_string()));
    assert!(actual.is_err());
    let err = *(actual.unwrap_err().downcast::<String>().unwrap());
    assert!(err.contains("Invalid"));
    

    #[should_panic]

    1 回复  |  直到 6 年前
        1
  •  4
  •   Andra    6 年前

    使用 #[should_panic(expected = "substring of panic message")]

    fn some_panic_function() {
        panic!("abc substring of panic message abc");
    }
    
    #[test]
    #[should_panic(expected = "substring of panic message")]
    fn test_some_panic_function() {
        some_panic_function();
    }
    

    从这里 https://doc.rust-lang.org/book/ch11-01-writing-tests.html

    推荐文章