简体   繁体   中英

Why do `assert_eq` and `assert_ne` exist when a simple `assert` will suffice?

assert!(a == b) takes less characters than assert_eq!(a, b) and, in my opinion, is more readable.

The error messages are more or less the same:

thread 'main' panicked at 'assertion failed: `(left == right)` (left: `1`, right: `2`)', src\main.rs:41

or

thread 'main' panicked at 'assertion failed: 1 == 2', src\main.rs:41

Actually, this question is not only about Rust; I keep seeing these different assert macros or functions in unit testing frameworks:

  • Cpputest has CHECK and CHECK_FALSE and CHECK_EQUAL and so on;
  • Googletest has EXPECT_GT and EXPECT_EQ and so on;
  • JUnit has assertEquals and assertFalse and do on.

Frequently there is also assert for some specific type like string or array. What's the point?

thread 'main' panicked at 'assertion failed: 1 == 2',

Your example is too simple to see that there is a great advantage in the use of assert_eq! . Consider this code:

let s = "Hello".to_string();
assert!(&s == "Bye");

This is the resulting panic message:

'assertion failed: &s == "Bye"'    

Now let's see what happens when we use assert_eq! :

let s = "Hello".to_string();
assert_eq!(&s, "Bye");

The message:

'assertion failed: `(left == right)` (left: `"Hello"`, right: `"Bye"`)'

This message provides much more insight than the former. Other unit testing systems often do the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM