在Rust中,使用thiserror
庫進行錯誤處理時,可以通過編寫單元測試來確保錯誤枚舉的正確實現。以下是一個簡單的示例,展示了如何使用thiserror
進行單元測試:
首先,創建一個使用thiserror
的錯誤枚舉:
// src/lib.rs
use thiserror::Error;
#[derive(Error, Debug)]
pub enum MyError {
#[error("An IO error occurred: {0}")]
IoError(#[from] std::io::Error),
#[error("A custom error occurred: {0}")]
CustomError(String),
}
接下來,編寫一個函數,該函數可能會返回上述錯誤:
// src/lib.rs
use std::fs::File;
use std::io::Read;
pub fn read_file_contents(file_path: &str) -> Result<String, MyError> {
let mut file = File::open(file_path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
現在,編寫一個單元測試來測試read_file_contents
函數和MyError
枚舉:
// tests/lib.rs
use super::*;
#[cfg(test)]
mod tests {
use std::io::Write;
#[test]
fn test_read_file_contents() {
// 創建一個測試文件
let mut test_file = File::create("test.txt").unwrap();
test_file.write_all(b"Test content").unwrap();
test_file.sync_all().unwrap();
// 測試成功讀取文件
let contents = read_file_contents("test.txt").unwrap();
assert_eq!(contents, "Test content");
// 測試IO錯誤
std::fs::remove_file("test.txt").unwrap();
assert!(read_file_contents("test.txt").is_err());
if let MyError::IoError(e) = read_file_contents("test.txt").unwrap_err() {
assert_eq!(e.to_string(), "An IO error occurred: Os { code: 2, kind: NotFound, message: \"No such file or directory\" }");
}
// 測試自定義錯誤
let mut test_file = File::create("test.txt").unwrap();
test_file.write_all(b"Test content").unwrap();
test_file.sync_all().unwrap();
std::fs::remove_file("test.txt").unwrap();
assert!(read_file_contents("test.txt").is_err());
if let MyError::CustomError(e) = read_file_contents("test.txt").unwrap_err() {
assert_eq!(e, "A custom error occurred: Custom error message");
}
}
}
在這個示例中,我們創建了一個名為test.txt
的測試文件,并在其中寫入了一些內容。然后,我們測試了read_file_contents
函數在不同情況下的行為,包括成功讀取文件、發生IO錯誤和自定義錯誤。通過這些測試,我們可以確保MyError
枚舉和read_file_contents
函數的正確實現。