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:
CHECK
and CHECK_FALSE
and CHECK_EQUAL
and so on;EXPECT_GT
and EXPECT_EQ
and so on;assertEquals
and assertFalse
and do on.Frequently there is also assert for some specific type like string or array. What's the point?
Macro std::assert_eqAsserts that two expressions are equal to each other (using PartialEq ). On panic, this macro will print the values of the expressions with their debug representations. Like assert! , this macro has a second form, where a custom panic message can be provided.
ASSERT: Fails fast, aborting the current function. EXPECT: Continues after the failure.
Python unittest – assertFalse() function This function will take two parameters as input and return a boolean value depending upon the assert condition. If test value is false then assertFalse() will return true else return false.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With