Skip to content

Commit 46474d2

Browse files
committed
fix #1067: explain that unit tests can return Result<()>
1 parent 9040387 commit 46474d2

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/testing/unit_testing.md

+28
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,33 @@ failures:
7070
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out
7171
```
7272

73+
## Tests and ?
74+
None of the previous unit test examples had a return type. But in Rust 2018, your unit tests can return Result<()>, which lets you use `?` in them! This can make them much more concise.
75+
76+
```rust,editable
77+
fn sqrt(number: f64) -> Result<f64, String> {
78+
if number >= 0.0 {
79+
Ok(number.powf(0.5))
80+
} else {
81+
Err("negative floats don't have square roots".to_owned())
82+
}
83+
}
84+
85+
#[cfg(test)]
86+
mod tests {
87+
use super::*;
88+
89+
#[test]
90+
fn test_sqrt() -> Result<(), String> {
91+
let x = 4.0;
92+
assert_eq!(sqrt(x)?.powf(2.0), x);
93+
Ok(())
94+
}
95+
}
96+
```
97+
98+
See [The Edition Guide][editionguide] for more details.
99+
73100
## Testing panics
74101

75102
To check functions that should panic under certain circumstances, use attribute
@@ -230,3 +257,4 @@ test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
230257
[panic]: ../std/panic.md
231258
[macros]: ../macros.md
232259
[mod]: ../mod.md
260+
[editionguide]: https://doc.rust-lang.org/edition-guide/rust-2018/error-handling-and-panics/question-mark-in-main-and-tests.html

0 commit comments

Comments
 (0)