Skip to content

Commit

Permalink
Fix mock example and move it to a file for testing
Browse files Browse the repository at this point in the history
I swear I tested this in an actual Rust file, but I somehow messed up
when copy-pasting it into the example. The code is now in the test
file so it will be correct.

Why is the indentation wrong? Because of

  rust-lang/mdBook#1564

The indentation is not kept by the included content, which breaks the
Markdown.
  • Loading branch information
mgeisler committed Dec 1, 2023
1 parent f837afa commit ecd16d0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 16 deletions.
18 changes: 17 additions & 1 deletion src/testing/mockall.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// ANCHOR: simple_example
use std::time::Duration;

#[mockall::automock]
Expand All @@ -6,8 +7,23 @@ pub trait Pet {
}

#[test]
fn test_robot_pet() {
fn test_robot_dog() {
let mut mock_dog = MockPet::new();
mock_dog.expect_is_hungry().return_const(true);
assert_eq!(mock_dog.is_hungry(Duration::from_secs(10)), true);
}
// ANCHOR_END: simple_example

// ANCHOR: extended_example
#[test]
fn test_robot_cat() {
let mut mock_cat = MockPet::new();
mock_cat
.expect_is_hungry()
.with(mockall::predicate::gt(Duration::from_secs(3 * 3600)))
.return_const(true);
mock_cat.expect_is_hungry().return_const(false);
assert_eq!(mock_cat.is_hungry(Duration::from_secs(1 * 3600)), false);
assert_eq!(mock_cat.is_hungry(Duration::from_secs(5 * 3600)), true);
}
// ANCHOR_END: extended_example
22 changes: 7 additions & 15 deletions src/testing/mocking.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ For mocking, [Mockall] is a widely used library. You need to refactor your
code to use traits, which you can then quickly mock:

```rust,ignore
{{#include mockall.rs}}
{{#include mockall.rs:simple_example}}
```

[Mockall]: https://docs.rs/mockall/
Expand Down Expand Up @@ -40,20 +40,12 @@ code to use traits, which you can then quickly mock:
existing Cargo project.

- Mockall has a lot more functionality. In particular, you can set up
expectations which depend on the arguments passed:

```rust,ignore
let mut mock_cat = MockPet::new();
mock_cat
.expect_is_hungry()
.with(mockall::predicate::gt(Duration::from_secs(3 * 3600)))
.return_const(true);
mock_cat
.expect_is_hungry()
.return_const(true);
assert_eq!(mock_cat.is_hungry(Duration::from_secs(1 * 3600)), false);
assert_eq!(mock_cat.is_hungry(Duration::from_secs(5 * 3600)), true);
```
expectations which depend on the arguments passed. Here we use this to mock a
cat which becomes hungry 3 hours after the last time it was fed:

```rust,ignore
{{#include mockall.rs:extended_example}}
```

- You can use `.times(n)` to limit the number of times a mock method can be
called to `n` --- the mock will automatically panic when dropped if this isn't
Expand Down

0 comments on commit ecd16d0

Please sign in to comment.