Reputation: 117
I've got this function that I want to test:
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.filename)?;
// -- snip
Ok(())
}
And this test:
#[test]
fn error_for_missing_file() {
let error = run(Config {
query: String::from("query"),
filename: String::from("not_a_real_file.txt"),
})
.unwrap_err();
let kind = error.kind(); // no method named `kind` found for struct `Box<dyn std::error::Error>` in the current scope
// assert to follow
}
How can I get the ErrorKind
from a Box?
Upvotes: 1
Views: 798
Reputation: 361605
std::error::Error
doesn't have a kind
method; it's a method of std::io::Error
. If you only have access to the base trait you won't be able to call it.
If you make that Box<dyn std::error::Error>
a std::io::Error
instead you'll have access to it. (And there's no need for a boxed trait object since std::io::Error
is a concrete struct.)
Better yet, you can return a std::io::Result<_>
, which is a Result
type specialized to hold std::io::Error
s:
use std::io;
pub fn run(config: Config) -> io::Result<()> {
let contents = fs::read_to_string(config.filename)?;
// -- snip
Ok(())
}
Upvotes: 3