簡體   English   中英

用拍手將參數傳遞給貨物測試

[英]Passing arguments to cargo test with clap

該程序采用配置文件的路徑。 例如cargo run -- -c path/to/yaml 然而,這不適用於貨物測試。 cargo test -- -c path/to/yaml會出現以下錯誤: error: Unrecognized option: 'c'

嘗試和研究

Clap 提供了一個方法fn from_args() -> Self ,但不完全知道這將如何解決問題。 通過使其成為集成測試並添加解決了類似的問題

[[test]]
name = "cpp_test"
# path = "tests/cpp_test.rs"   # This is automatic; you can use a different path if you really want to.
harness = false

到 cargo.toml 文件。
就我而言,我想測試一些功能,從而進行單元測試。 我不相信這會奏效。

我認為最簡單的方法是讓fn main_body(args: Args)完成真正的工作,然后通過直接在源代碼中而不是在命令行中傳遞 args 來測試main_body

use clap::Parser; // 3.1.18

#[derive(Parser)]
struct Args {
    #[clap(short, long)]
    name: String,
}

fn main_body(args: Args) -> Result<(), ()> {
    // Your main body here
    Ok(())
}

fn main() -> Result<(), ()> {
    let args = Args::parse();
    main_body(args)
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test() {
        let args = Args { name: "Bob".into() };
        assert_eq!(main_body(args), Ok(()));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM