Amomum
Amomum

Reputation: 6503

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:

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

Upvotes: 15

Views: 6739

Answers (1)

E_net4
E_net4

Reputation: 30042

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.

Upvotes: 21

Related Questions