Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 295
Amomum Avatar asked May 03 '17 18:05

Amomum


People also ask

What does Assert_eq do in Rust?

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.

What is the difference between assert and expect?

ASSERT: Fails fast, aborting the current function. EXPECT: Continues after the failure.

How do you assert false in Python?

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.


1 Answers

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.

like image 156
E_net4 stands with Ukraine Avatar answered Nov 16 '22 02:11

E_net4 stands with Ukraine