# How to use pretty_assertions for Rust test cases

Below, you’ll find a set of exercises designed to help you practice with the pretty\_assertion crate in Rust. Each exercise focuses on a commonly used feature of `pretty_assertions` and follows the structure:

1.  Feature Explanation
    
2.  Working Example
    
3.  Exercise
    
4.  Solution (with detailed explanation)
    

Make sure you add `pretty_assertions` to your development dependencies in `Cargo.toml`:

```rust
[dev-dependencies]
pretty_assertions = "1.3"
```

Import its macros in your test files:

```rust
use pretty_assertions::{assert_eq, assert_ne};
```

## Basic `assert_eq!` with Pretty Printed Differences

### Feature Explanation

At its core, `pretty_assertions` replaces the standard `assert_eq!` and `assert_ne!` macros with a version that highlights differences in a much more straightforward, color-coded way. This is extremely helpful when you compare large strings or data structures. The usage is almost identical to Rust’s built-in `assert_eq!` and `assert_ne!`, but if the test fails, you get a pretty diff.

### Example

In the following test, we intentionally have a failure scenario to show off the diff. We’ll see a better diff than the default when comparing two different strings.

```rust
use pretty_assertions::{assert_eq, assert_ne};

#[test]
#[should_panic]
fn test_failure_example() {
    let actual = "Hello, Rust!";
    let expected = "Hello, World!";
    assert_eq!(actual, expected);
}
```

f you run this, you’ll see a panic that includes colored highlights showing what’s different between ***"Rust!"*** and ***"World!"***.

### Exercise - 1

**Goal**: Create a test that compares two *identical* strings, e.g., ***"Hello, World!"*** vs. ***"Hello, World!"***, and ensures they are equal using **assert\_eq!**. Name the test something like **test\_equal\_strings**. The test should **pass**, not panic.

### Example

In the snippet below, we check that the two strings are unequal. If they were the same, we’d see a panic with a diff highlighting that there's no difference.

```rust
use pretty_assertions::{assert_eq, assert_ne};

#[test]
fn test_ne_example() {
    let s1 = "Apple";
    let s2 = "Orange";
    assert_ne!(s1, s2);
}
```

### Exercise - 2

**Goal**: Write a test that uses **assert\_ne!** to check that two integers **10** and **20** are not equal. Name the test **test\_numbers\_not\_equal**. The test should pass if the integers differ.

## Comparing Multiline Strings

### Feature Explanation

One of the best features of **pretty\_assertions** is how it highlights differences between large or multiline strings. Regular assert\_eq! can be hard to read when outputs are multiline. With **pretty\_assertions**, you get line-by-line diffs, similar to a Git diff.

### Example

In this example, we compare two multiline strings. One has an extra comma that causes them to differ. If the test fails, you’ll see exactly which line is different, with coloring (if your terminal supports it).

```rust
use pretty_assertions::{assert_eq, assert_ne};

#[test]
#[should_panic]
fn test_multiline_example() {
    let multi1 = "Line1\nLine2\nLine3";
    let multi2 = "Line1\nLine2,\nLine3";
    assert_eq!(multi1, multi2);
}
```

### Exercise - 3

**Goal**: Create a new test named **test\_multiline\_strings** in which you compare two multiline strings that are *identical*. Use a string with at least three lines. The test should pass. This will illustrate that **pretty\_assertions** can handle multiline strings without showing a diff if they match perfectly.

## Comparing Complex Data Structures (e.g., Vectors or HashMaps)

### Feature Explanation

**pretty\_assertions** also prettifies diffs for complex data structures (such as Vec, HashMap, and custom structs that implement Debug). If you have large nested data, the differences are shown in a more structured and readable format.

### Example

Below, we demonstrate how to compare two vectors of integers. If they differ, you’ll see a clear, line-by-line breakdown of which items mismatch:

```rust
use pretty_assertions::{assert_eq, assert_ne};

#[test]
#[should_panic]
fn test_vector_example() {
    let v1 = vec![1, 2, 3, 4];
    let v2 = vec![1, 2, 5, 4];
    assert_eq!(v1, v2);
}
```

### Exercise - 4

**Goal:** Write a test that compares two **HashMap<u32, &str>**. They should be *identical.* Name the test **test\_hashmap\_equality**, and verify that **pretty\_assertions** can handle the comparison without error. Include at least two key-value pairs.

> **Tip**: Don’t forget to **use std::collections::HashMap** at the top.

## Custom Types that Implement Debug

### Feature Explanation

**pretty\_assertions** relies on types implementing the **Debug** trait to render differences. For your custom structs, as long as they implement **Debug**, the crate can show a diff if they differ.

### Example

Here, we have a struct **Point** with **x** and **y** coordinates. If we compare two different instances, we’ll see a color-coded difference highlighting which fields differ:

```rust
use pretty_assertions::{assert_eq, assert_ne};

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

#[test]
#[should_panic]
fn test_custom_struct_example() {
    let p1 = Point { x: 1, y: 2 };
    let p2 = Point { x: 1, y: 3 };
    assert_eq!(p1, p2);
}
```

### Exercise - 5

**Goal**: Create a struct named **User** with fields **id: u32** and **name: String**. Implement **Debug** (derive it) for the struct. Write a test **test\_user\_struct\_equality** comparing two *identical* **User** instances. The test should pass.

## Solutions

In this section, you can find the solutions to the exercises above.

### Solution - 1

```rust
use pretty_assertions::{assert_eq, assert_ne};

#[test]
fn test_equal_strings() {
    let actual = "Hello, World!";
    let expected = "Hello, World!";
    assert_eq!(actual, expected);
}
```

**Explanation**:

*   We import **assert\_eq** from **pretty\_assertions**.
    
*   We compare two identical strings.
    
*   Because they’re equal, the test passes, and you won’t see any diff output.
    
*   The point is to illustrate the usage of **assert\_eq** from **pretty\_assertions** in a test that succeeds.
    

### Solution - 2

```rust
use pretty_assertions::{assert_eq, assert_ne};

#[test]
fn test_numbers_not_equal() {
    let num1 = 10;
    let num2 = 20;
    assert_ne!(num1, num2);
}
```

**Explanation**:

*   We’re verifying that **10** and **20** are unequal.
    
*   **assert\_ne!(num1, num2)** will pass since the values differ.
    
*   If they were the same, we’d see a diff that highlights zero differences (which is ironically helpful if you made a mistake in your test logic).
    

### Solution - 3

```rust
use pretty_assertions::{assert_eq, assert_ne};

#[test]
fn test_multiline_strings() {
    let expected = "foo\nbar\nbaz";
    let actual = "foo\nbar\nbaz";
    assert_eq!(expected, actual);
}
```

**Explanation**:

*   We define two multiline strings, *expected* and *actual*.
    
*   Both strings are identical.
    
*   Because they match exactly, **assert\_eq!** succeeds silently (no diff needed).
    

### Solution - 4

```rust
use std::collections::HashMap;
use pretty_assertions::{assert_eq, assert_ne};


#[test]
fn test_hashmap_equality() {
    let mut map1 = HashMap::new();
    map1.insert(1, "one");
    map1.insert(2, "two");

    let mut map2 = HashMap::new();
    map2.insert(1, "one");
    map2.insert(2, "two");

    // They are identical, so this will pass silently
    assert_eq!(map1, map2);
}
```

**Explanation:**

*   We create two **HashMap<u32, &str>** with the same key-value pairs.
    
*   **assert\_eq!(map1, map2)** passes without showing any diff.
    
*   If there was a difference, we’d see a pretty-printed structure comparison.
    

### Solution - 5

```rust
use pretty_assertions::{assert_eq, assert_ne};

#[derive(Debug)]
struct User {
    id: u32,
    name: String,
}


#[test]
fn test_user_struct_equality() {
    let user1 = User {
        id: 101,
        name: String::from("Alice"),
    };

    let user2 = User {
        id: 101,
        name: String::from("Alice"),
    };

    // Since user1 == user2, the test passes silently
    assert_eq!(user1.id, user2.id);
    assert_eq!(user1.name, user2.name);

    // Optionally, you could also do:
    // assert_eq!(user1, user2);
    // But that requires PartialEq on the struct as well!
}
```

**Note**: If you want to compare the User instances directly (not just their fields), also derive PartialEq so that Rust knows how to determine the equality of your struct:

```rust
#[derive(Debug, PartialEq)]
struct User { ... }
```

Then you can do **assert\_eq!(user1, user2);** directly.

**Explanation:**

*   We define **struct User** with **derive(Debug)** so it can be printed.
    
*   We create two identical instances, **user1** and **user2**.
    
*   We compare their fields with **assert\_eq!**.
    
*   Alternatively, if we derived **PartialEq**, we could compare the structs directly.
    

This exercise shows how **pretty\_assertions** can help you debug differences in custom types, provided those types implement **Debug** (and optionally **PartialEq** if you want to compare them directly).

## Wrap-Up

By working through these exercises, you’ve practiced many of the key features of **pretty\_assertions**:

*   Replacing standard **assert\_eq!** and **assert\_ne!** macros to get prettier diffs.
    
*   Comparing everything from basic data (ints, strings) to complex data structures (vectors, hash maps) and custom types.
    
*   Observing how multiline strings and large data structures get clearer, color-coded highlights for any differences.
    

> You can have a look at the code examples above on GitHub here: https://github.com/DigitalDevBlog/pretty\_assertions\_examples.git

Enjoy more explicit test failures—and debug faster!
