小编dat*_*rom的帖子

是否有更简洁的方法来测试使用需要用户在 Rust 中输入的函数的函数?

我正在为我的第一个 Rust 项目编写一个CLI 问题询问库,因为我可能无论如何都会使用它,而且我找不到一种干净的方法来测试terminal构建器模式的方法,该方法使用配置获取用户输入并返回答案。

pub fn confirm(&mut self) -> Answer {
    self.yes_no();
    self.build_prompt();
    let prompt = self.prompt.clone();
    let valid_responses = self.valid_responses.clone().unwrap();
    loop {
        let stdio = io::stdin();
        let input = stdio.lock();
        let output = io::stdout();
        if let Ok(response) = prompt_user(input, output, &prompt) {
            for key in valid_responses.keys() {
                if *response.trim().to_lowercase() == *key {
                    return valid_responses.get(key).unwrap().clone();
                }
            }
            self.build_clarification();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在寻找解决方案时,我发现了依赖注入,它允许我为提示用户使用Cursor. 它不允许我confirm()为每个测试更改用户对函数的输入,Question::new("Continue?").confirm()所以我尝试使用条件编译,并提出以下内容。

#[cfg(not(test))]
fn prompt_user<R, W>(mut reader: …
Run Code Online (Sandbox Code Playgroud)

unit-testing rust

2
推荐指数
1
解决办法
1097
查看次数

标签 统计

rust ×1

unit-testing ×1