[英]How to test instantiation of struct in Rust?
我有以下struct
:
pub struct Settings {
pub something: String
}
使用以下構造函數:
impl Settings {
fn new(path: &Path) -> Settings {
if !path.exists() {
fail!("Configuration file not found.");
}
return Settings{something:String::new()};
}
}
我創建了一個單元測試,以查看使用Path
指向現有文件和不存在現有文件的結構時會發生什么情況:
mod tests {
#[test]
fn test_new_valid_path() {
use configuration::Settings;
let path = &Path::new("emperor.ini");
let settings = Settings::new(path);
assert!(settings);
}
#[test]
fn test_new_invalid_path() {
use configuration::Settings;
let path = &Path::new("emperor.xml");
let settings = Settings::new(path);
}
}
但是當我這樣運行測試時: rustc --test meh.rs; ./meh --nocapture
rustc --test meh.rs; ./meh --nocapture
我得到以下輸出:
<std macros>:3:12: 40:20 error: cannot apply unary operator `!` to type `configuration::Settings`
<std macros>:3 if !$cond {
<std macros>:4 fail!("assertion failed: {:s}", stringify!($cond))
<std macros>:5 }
<std macros>:6 );
<std macros>:7 ($cond:expr, $($arg:expr),+) => (
<std macros>:8 if !$cond {
...
<std macros>:1:1: 12:2 note: in expansion of assert!
shogun.rs:40:4: 40:22 note: expansion site
error: aborting due to previous error
如何測試結構實例化?
我認為您誤解了這些事物如何運作的模型。
返回類型為Settings
函數-好吧,它返回時的值是可以正確實例化的Settings
對象。 如果我們刪除了您的assert!(settings);
行,代碼將完全滿足您的需求。 (順便說一句, assert!
期望布爾值作為其第一個參數,就if
需要布爾值表達式來跟隨它一樣。)
如果該路徑不存在,則fail!
將起作用,任務將失敗,展開; Settings::new
呼叫永不返回。 觸發任務失敗也正是assert!(…)
所做的。
換句話說:執行該行的事實證明它已正確初始化。
順便說一句,那樣的失敗通常被認為是不好的形式。 更好的方法是返回Option<Settings>
,而不要使用名稱new
,而是使用某種指示您將從文件中加載它的名稱; 像這樣的東西:
impl Settings {
fn load(path: &Path) -> Option<Settings> {
if !path.exists() {
None
} else {
Some(Settings { something: String::new() })
}
}
}
我認為問題是這條線
assert!(settings);
如果其中的布爾參數為false,則assert只會引發錯誤,但是在這種情況下,設置不是布爾值,它的類型為configuration :: Settings
cannot apply unary operator `!` to type `configuration::Settings`
要測試是否有有效的設置,請執行以下操作
assert!(settings.something.is_empty())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.