You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In Chapter 11.1 - How to Write Tests - at the bottom of the page it is explained, how to
write a test, when we expect the compiler to panic. The book then goes on to explain how to write a test, when we expect Result::Ok, but when it comes to an expected Result::Err is only states:
You can’t use the #[should_panic] annotation on tests that use Result<T, E>.
Instead, you should return an Err value directly when the test should fail.
I interpret this as we have to write something in the lines of:
#[test]
fn expect_err() -> Result::Err {
Err(String::from("This is an expected error"))
}
This doesn't work because Result::Err is a variant, not a type.
I've found these two ways to test for Result:Err:
#[test]
fn expect_err() {
let res: Result<(), &str> = Err("This is an expected error");
res.expect_err("This should have panicked");
// or
assert_eq!(res.is_ok(), false);
}
It would be nice if there was a code example, after the quoted sentence.
Thank you very much to everyone who worked on the book. I thoroughly enjoy it.
The text was updated successfully, but these errors were encountered:
carols10cents
changed the title
Chapter 11.1 - Request for an example of a test with expected Result::Err
Chapter 11.1 - Explain that it's not possible to expect a test to return an error when the return type is Result
Nov 28, 2021
Yep, it's not possible to do #[should_panic] with a test that returns Result. The purpose of having a test function return Result is so that you can use ? in the test to mean "this operation should succeed, if not, fail the test".
The way to check that an operation within a test returns an Err as expected is to not use ? on that value, but instead use assert!(val.is_err()) or val.expect_err(...) or match.
Hy,
In Chapter 11.1 - How to Write Tests - at the bottom of the page it is explained, how to
write a test, when we expect the compiler to panic. The book then goes on to explain how to write a test, when we expect Result::Ok, but when it comes to an expected Result::Err is only states:
I interpret this as we have to write something in the lines of:
This doesn't work because Result::Err is a variant, not a type.
I've found these two ways to test for Result:Err:
It would be nice if there was a code example, after the quoted sentence.
Thank you very much to everyone who worked on the book. I thoroughly enjoy it.
The text was updated successfully, but these errors were encountered: