Unit Testing
assert_ne!
The assert_ne! macro asserts that two expressions are not equal according to the PartialEq trait (left != right). If the two expressions compare equal, assert_ne! panics and prints the Debug representation of both left and right.
assert_ne!(left, right)
assert_ne!(left, right, "custom message: {}", context)
When to Use assert_ne!
assert_ne! is preferred over assert!(a != b) whenever you want the test failure output to display the offending value that unexpectedly matched:
- Verifying that a state transition, mutation, or encryption step actually modified its input.
- Verifying that unique ID generators, token generators, or port allocators produce distinct values on consecutive calls.
- Checking that a hash or redact function does not return the cleartext secret.
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_ID: AtomicU64 = AtomicU64::new(1000);
fn generate_request_id() -> u64 {
NEXT_ID.fetch_add(1, Ordering::Relaxed)
}
fn redact_token(token: &str) -> String {
if token.len() <= 4 {
"****".to_string()
} else {
format!("{}...****", &token[..4])
}
}
fn main() {
let id_first = generate_request_id();
let id_second = generate_request_id();
// Verify consecutive IDs are distinct
assert_ne!(id_first, id_second, "request IDs must be unique");
// Verify redaction never equals the raw secret
let raw_secret = "sk_live_987654321";
let redacted = redact_token(raw_secret);
assert_ne!(redacted, raw_secret, "redacted output leaked raw secret");
println!("Generated distinct IDs: {id_first} != {id_second}");
println!("Redacted token: {redacted}");
}
Generated distinct IDs: 1000 != 1001
Redacted token: sk_l...****
Failure Output of assert_ne!
When left != right evaluates to false, assert_ne! prints both operands along with any custom diagnostic message:
fn main() {
let primary_host = "db-node-1.internal";
let replica_host = "db-node-1.internal";
assert_ne!(
primary_host, replica_host,
"failover replica must not point to the primary host"
);
}
thread 'main' panicked at src/main.rs:5:5:
assertion `left != right` failed: failover replica must not point to the primary host
left: "db-node-1.internal"
right: "db-node-1.internal"
Comparing Rust's Standard Assertion Macros
| Macro | Condition Checked | Required Traits | Release Build Behavior |
|---|---|---|---|
assert!(cond) |
cond == true |
cond: bool |
Active |
assert_eq!(a, b) |
a == b |
PartialEq + Debug |
Active |
assert_ne!(a, b) |
a != b |
PartialEq + Debug |
Active |
debug_assert!(cond) |
cond == true |
cond: bool |
Stripped by default |
debug_assert_eq!(a, b) |
a == b |
PartialEq + Debug |
Stripped by default |
debug_assert_ne!(a, b) |
a != b |
PartialEq + Debug |
Stripped by default |